Skip to content
Kevin Leong edited this page Nov 14, 2016 · 5 revisions

UITableView

UITableViewDelegate and UITableViewDatasource

A view controller at a minimum must adhere to the UITableViewDelegate and UITableViewDatasource protocols.

Infinite scroll

Pull to refresh

UIRefreshControls are designed to work only with UITableViews or UITableViewControllers.

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!

    var refreshControl = UIRefreshControl()

    override func viewDidLoad() {
        super.viewDidLoad()

        /*
            A UIRefreshControl sends a `valueChanged` event to signal
            when a refresh should occur.
        */
        refreshControl.addTarget(self, action: #selector(ViewController.refresh), for: .valueChanged)
        tableView.addSubview(refreshControl)
    }

    @objc private func refresh() {
        ...
        // Hide refresh control
        if refreshControl.isRefreshing {
            refreshControl.endRefreshing()
        }
    }

References

Dynamic cell height

To allow AutoLayout to dynamically size UITableViewCell instances, the following two lines are necessary in a view controller.

tableView.estimatedRowHeight = 100.0
tableView.rowHeight = UITableViewAutomaticDimension

Usually, cell height is defined by the tableView:heightForRowAtIndexPath method from the UITableViewDelegate protocol.

estimatedRowHeight gives the tableView an approximate height for each cell. This value is used to calculate scroll bar heights and positioning, among other things.

tableView.estimatedRowHeight = 100.0

Automatic sizing uses AutoLayout constraints to calculate height.

tableView.rowHeight = UITableViewAutomaticDimension

Both estimatedRowHeight and UITableViewAutomaticDimension must be set.

References

References

Clone this wiki locally