Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active December 22, 2018 08:16
Show Gist options
  • Save KentarouKanno/78e34a7955f089f29a16b1c77681911e to your computer and use it in GitHub Desktop.
Save KentarouKanno/78e34a7955f089f29a16b1c77681911e to your computer and use it in GitHub Desktop.
UITableView

UITableView

★ Autolayoutサンプル
TableView Autolayout Sample


★ TableViewのスクロールが一番下まで到達したかの判定

// UIScrollViewDelegateを適用

func scrollViewDidScroll(scrollView: UIScrollView) {
    if myTableView.contentOffset.y + myTableView.frame.size.height > myTableView.contentSize.height {
        print("一番下に到達した時の処理")
    }
}

★ 画面に見えている部分のセルを取得する

let visibleCells = tableView.visibleCells as! [CustomCell]
for cell in visibleCells {
    
    // 見えている部分のセルに対しての処理
}

★ 画面に見えているセルでセルのFrameが全て見えているもセルを抽出する

let perfectVisibleCells = tableView.visibleCells.filter {
    return tableView.bounds.contains($0.frame)
}

★ cell.textLabelを複数行に対応し自動でセルの高さを計算する

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var myTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")

        myTableView.estimatedRowHeight = 20
        myTableView.rowHeight = UITableViewAutomaticDimension
    }

    // Data Array
    var dataArray = ["複数行文字1、複数行文字1、複数行文字1、複数行文字1、複数行文字1、複数行文字1、複数行文字1","複数行文字2、複数行文字2、複数行文字2、複数行文字2","文字3","文字4","文字5","文字6","文字7"]

    // Row Count
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }

    // Generate Cell
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        cell.textLabel?.numberOfLines = 0
        cell.textLabel?.text = dataArray[indexPath.row]
        return cell
    }
}

★ Section Headerをテーブルと一緒にスクロールさせる
UITableViewでSectionHeader/SectionFooterを残さない方法

func scrollViewDidScroll(scrollView: UIScrollView) {
    
    let sectionHeaderHeight = self.tableView.sectionHeaderHeight
    let  offsetY = scrollView.contentOffset.y
    
    if offsetY <= sectionHeaderHeight && offsetY >= 0 {
        scrollView.contentInset = UIEdgeInsets(top: -offsetY, left: 0, bottom: 0, right: 0)
    } else if offsetY >= sectionHeaderHeight {
        scrollView.contentInset = UIEdgeInsets(top: -sectionHeaderHeight, left: 0, bottom: 0, right: 0)
    }
}

★ TableViewのSeparatorの左マージンをなしにする

cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsetsZero
cell.layoutMargins  = UIEdgeInsetsZero

★ 複数のセクションをアニメーション付きで削除する

let sections = IndexSet(2...4)
tableView.deleteSections(sections, with: .fade)

★ TablViewの高さを返す

/// 各TableViewCellの高さを保持する配列
var heightAtIndexPath = NSMutableDictionary()

// MARK: - UITableViewDelegate

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    
    guard let height = heightAtIndexPath.object(forKey: indexPath) as? CGFloat else {
        return UITableViewAutomaticDimension
    }
    return height
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    let height = cell.frame.size.height
    heightAtIndexPath.setObject(height, forKey: indexPath as NSCopying)
}

/// Dictionary使用👇

/// TableViewCellの高さを保持する配列
private var heightAtIndexPath: [IndexPath: CGFloat] = [:]


func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    if let height: CGFloat = heightAtIndexPath[indexPath] {
        return height
    } else {
        return UITableView.automaticDimension
    }
}

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    heightAtIndexPath[indexPath] = cell.frame.size.height
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment