UITableView is a powerful and versatile component in iOS development, allowing you to display lists of data in a scrollable view. Whether you are creating a simple list or a complex data-driven application, understanding how to implement a UITableView is essential. In this article, we’ll walk through three diverse examples of implementing a UITableView in Swift, each designed to illustrate different scenarios.
In this example, we’ll create a simple UITableView that displays a list of fruits. This is a great starting point for beginners to understand the basic setup of UITableView.
import UIKit
class FruitsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
override func viewDidLoad() {
super.viewDidLoad()
let tableView = UITableView(frame: self.view.bounds)
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruits.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = fruits[indexPath.row]
return cell
}
}
fruits
array contains the items displayed in the table.In this example, we’ll implement a UITableView that fetches and displays a list of users from a mock API. This example demonstrates how to populate a UITableView with dynamic data.
import UIKit
struct User {
let name: String
}
class UsersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var users: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
fetchUsers()
let tableView = UITableView(frame: self.view.bounds)
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(tableView)
}
func fetchUsers() {
// Mock API data
users = [User(name: "John Doe"), User(name: "Jane Smith"), User(name: "Sam Brown")]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = users[indexPath.row].name
return cell
}
}
users
array.In this example, we’ll create a UITableView that displays a list of books with custom cells. This will help you understand how to design and use custom UITableViewCell subclasses.
import UIKit
class Book {
let title: String
let author: String
init(title: String, author: String) {
self.title = title
self.author = author
}
}
class BookCell: UITableViewCell {
let titleLabel = UILabel()
let authorLabel = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(titleLabel)
contentView.addSubview(authorLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
authorLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10),
titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
authorLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10),
authorLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 5)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class BooksViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var books: [Book] = [
Book(title: "1984", author: "George Orwell"),
Book(title: "To Kill a Mockingbird", author: "Harper Lee"),
Book(title: "Moby Dick", author: "Herman Melville")
]
override func viewDidLoad() {
super.viewDidLoad()
let tableView = UITableView(frame: self.view.bounds)
tableView.register(BookCell.self, forCellReuseIdentifier: "bookCell")
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return books.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "bookCell", for: indexPath) as! BookCell
cell.titleLabel.text = books[indexPath.row].title
cell.authorLabel.text = books[indexPath.row].author
return cell
}
}
These examples of implementing a UITableView in Swift should provide you with a clear understanding of how to use this powerful component. Whether you’re displaying static data, dynamic data, or custom cells, you now have a solid foundation to build upon in your iOS development journey.