create uitableview in swift

To create UITableView in Swift, there are basically two steps:

  1. Setting up UITableView in a view controller,
  2. Implementing Datasource methods to provide data to the tableview.

Setting up UITableView

Here are the steps to create UITableView :

  1. Drag and drop UITableViewController or simply UIView and add a UITableView instance to it using the storyboard.
  2. Add constraints to the UITableView instance.
  3. Create a UITableViewCell custom class (optional) to render content inside the cell.
  4. Connect the UITableView instance to the view controller by creating an IBOutlet and adding a delegate and data source property to the view controller.

Implementing Datasource methods

main.swift
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tableView: UITableView!
    
    var items: [String] = ["Item 1", "Item 2", "Item 3"]

    override func viewDidLoad() {
        super.viewDidLoad()

        // set the delegate and datasource methods to the view controller
        tableView.delegate = self
        tableView.dataSource = self
    }

    // number of sections
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    // number of rows in the table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    // display the cell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
        let item = items[indexPath.row]
        cell.itemLabel?.text = item
        return cell
    }

    // add action when cell was selected
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        print(items[indexPath.row])
    }
}
1252 chars
39 lines

In the above code snippet, we set UITableViewController as primary view controller or simply add a view with UITableView instance added to it by using IBOutlet. We set data source and delegate of UITableView to the view controller. We created an array of string items and provided item to cell by using the cellForRowAt Datasource method.

We also implemented didSelectRowAt TableView method to provide user feedback on cell selection.

Note: The above example assumes that you have created a custom TableViewCell subclass named CustomTableViewCell with a UILabel named itemLabel.

gistlibby LogSnag