tableviewcontrolelr with models and designated cells in swift

To create a UITableView with models and designated cells in Swift, you can follow these steps:

  1. Create a new file for your model.
main.swift
class Item {
    var itemName: String
    var itemDescription: String

    init(itemName: String, itemDescription: String) {
        self.itemName = itemName
        self.itemDescription = itemDescription
    }
}
213 chars
10 lines
  1. Create a new file for your custom cell. You can create a .xib file for your cell or create a custom subclass of UITableViewCell in your project.

  2. In your UIViewController, create an IBOutlet for your UITableView.

main.swift
@IBOutlet weak var tableView: UITableView!
43 chars
2 lines
  1. In your UIViewController, create an array to hold your Item models.
main.swift
var items = [Item]()
21 chars
2 lines
  1. In viewDidLoad(), register your custom cell to the table view and set the dataSource and delegate to the view controller.
main.swift
override func viewDidLoad() {
    super.viewDidLoad()

    tableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "CustomTableViewCell")

    tableView.dataSource = self
    tableView.delegate = self
}
242 chars
9 lines
  1. Implement the UITableViewDataSource methods in your view controller to retrieve and display the data in your UITableView.
main.swift
extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell

        let item = items[indexPath.row]

        cell.titleLabel.text = item.itemName
        cell.descriptionLabel.text = item.itemDescription

        return cell
    }
}
577 chars
17 lines
  1. Implement the UITableViewDelegate method didSelectRowAt to handle user interaction with the table view.
main.swift
extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // Handle user selection of table view cell
    }
}
192 chars
6 lines

With these steps, you should now have a UITableView with models and designated cells in Swift.

gistlibby LogSnag