How do I manage table views and collection views in Swift?

Managing table views and collection views in Swift can enhance the user interface of your iOS applications. Below are examples of how to implement and manage these views effectively.

Table Views Example

import UIKit class TableViewController: UITableViewController { let items = ["Item 1", "Item 2", "Item 3"] override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = items[indexPath.row] return cell } }

Collection Views Example

import UIKit class CollectionViewController: UICollectionViewController { let items = ["Item 1", "Item 2", "Item 3"] override func viewDidLoad() { super.viewDidLoad() collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell") } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) // Configure your cell here return cell } }

Swift iOS UITableView UICollectionView UITableViewController UICollectionViewController