tableviewcontrolelr with models in swift

To display data using UITableView in iOS with Swift, the following steps can be taken:

  1. Create a new class or struct for the model that will hold the data to be displayed in the UITableView. For example, if you want to display a list of contacts, you can create a Contact struct with properties like name, phone number, and email.
main.swift
struct Contact {
    let name: String
    let phoneNumber: String
    let email: String
}
90 chars
6 lines
  1. Create a new UITableView in your storyboard or programmatically. Set its delegate and data source to the view controller that will manage the table view.
main.swift
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // set delegate and data source
        tableView.delegate = self
        tableView.dataSource = self
    }
}
315 chars
13 lines
  1. Implement the UITableViewDataSource protocol methods in your view controller, such as numberOfRowsInSection and cellForRowAtIndexPath. Use the model data to populate the cells.
main.swift
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // return the number of contacts
    return contacts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // dequeue a cell
    let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath)

    // get the contact for this row
    let contact = contacts[indexPath.row]

    // configure the cell with the contact data
    cell.textLabel?.text = contact.name
    cell.detailTextLabel?.text = contact.phoneNumber

    return cell
}
603 chars
19 lines
  1. Optionally, implement UITableViewDelegate protocol methods to handle user interaction with the table view, such as didSelectRowAtIndexPath.

With these steps, you can easily set up a UITableViewController with models in Swift, making it easy to display and interact with data in your app.

gistlibby LogSnag