create a table view with custom cells in swift

To create a custom table view cell, follow these steps:

  1. Create a new file in your Xcode project by selecting File > New > File... and choosing iOS > Cocoa Touch Class.

  2. Name the file "CustomTableViewCell" and make sure it is a subclass of UITableViewCell.

  3. In the CustomTableViewCell.swift file, add the necessary outlets for the cell's UI elements as follows:

main.swift
class CustomTableViewCell: UITableViewCell {
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UILabel!
    @IBOutlet weak var iconImageView: UIImageView!
}
191 chars
6 lines
  1. Open your storyboard and add a new table view controller to your view.

  2. Drag a table view cell from the Object Library onto the table view.

  3. In the Identity Inspector, set the cell's class to "CustomTableViewCell".

  4. Customize the cell's layout by adding UI elements like labels and image views.

  5. In the Attributes Inspector, give the cell a unique identifier like "CustomCell".

  6. In the table view controller's code, implement the UITableViewDataSource and UITableViewDelegate protocols.

  7. Add a new method to your code to dequeue the custom cell, as follows:

main.swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
    
    cell.nameLabel.text = "Custom cell name"
    cell.descriptionLabel.text = "Custom cell description"
    cell.iconImageView.image = UIImage(named: "custom_icon")
    
    return cell
}
405 chars
10 lines
  1. Run your app and the custom table view cells should be displayed in the table view.

gistlibby LogSnag