UITableView Implementation Examples in Swift

Explore practical examples of implementing a UITableView in Swift, perfect for beginners and experienced developers alike.
By Taylor

Introduction to UITableView in Swift

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.

Example 1: Basic UITableView with Static Data

Context

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
    }
}

Notes

  • This example creates a UITableView with static data. The fruits array contains the items displayed in the table.
  • Remember to set the delegate and data source to the view controller to handle table view data.

Example 2: UITableView with Dynamic Data

Context

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
    }
}

Notes

  • In this example, we simulate fetching user data and populating the users array.
  • For real applications, consider using URLSession to make network requests for dynamic data.

Example 3: UITableView with Custom Cells

Context

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
    }
}

Notes

  • This example demonstrates how to create a custom cell with additional labels for displaying book details.
  • Don’t forget to register your custom cell class with the UITableView before dequeuing cells.

Conclusion

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.