create table view in swift

Here are the steps to create a table view in Swift:

  1. Create a new project in Xcode
  2. Open the storyboard and drag a TableView onto the view controller
  3. Create a new subclass of UITableViewController
  4. Make sure the TableView in storyboard is selected
  5. In the Identity Inspector, set the custom class to the UITableViewController you just created
  6. In the attributes inspector, set the number of prototype cells to the number you will need
  7. Drag objects onto the prototype cells to create the layout of your cells
  8. Create an IBOutlet for the TableView in your UITableViewController
  9. Implement the UITableViewDataSource and UITableViewDelegate protocols

Here's an example code snippet for the required UITableViewDataSource and UITableViewDelegate methods:

main.swift
class ViewController: UITableViewController {

    override func numberOfSections(in tableView: UITableView) -> Int {
        // Return the number of sections
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of rows
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Dequeue a reusable cell and set up the cell's contents
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        // Configure the cell...
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // Handle row selection...
    }
}
770 chars
22 lines

Note: don't forget to set the identifier of the prototype cell in storyboard, as shown in the example above.

related categories

gistlibby LogSnag