How do I implement custom cells and layouts in Swift?

In Swift, custom cells and layouts can greatly enhance the user interface of your application. Utilizing UITableView and UICollectionView allows for flexible and dynamic layouts tailored to your specific needs.

Here’s a brief guide on how to create custom cells for a UITableView:

// CustomTableViewCell.swift import UIKit class CustomTableViewCell: UITableViewCell { @IBOutlet weak var customLabel: UILabel! @IBOutlet weak var customImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func configure(with text: String, image: UIImage) { customLabel.text = text customImageView.image = image } }

To use the custom cell, implement the following in your UITableViewController:

class CustomTableViewController: UITableViewController { let data = [("Item 1", UIImage()), ("Item 2", UIImage())] // Example data override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell let item = data[indexPath.row] cell.configure(with: item.0, image: item.1) return cell } }

This is a simple implementation of custom cells. As you explore further, you can create more complex layouts using UICollectionView where you can define different layout structures.


Custom cells UITableView UICollectionView Swift UI iOS development