DEV Community

Cover image for Building a UITableView Programmatically
Aaron Cleveland
Aaron Cleveland

Posted on

Building a UITableView Programmatically

As a user, we start up our application on our device and we never know what is exactly going on in our application. All we know is that this application is "Gorgeous, Beautiful, and even Spectacular". But as a developer, we know what is going on in the code without looking at the code. We can tell this is a UITableView or even possibly a UICollectionView.

Today we are going to look just at UITableView. Specifically, we are going to look at building a 'UITableView' programmatically. Let's look at two ways we can build this out. One is by creating our UITableView via a function that gives us the ability to call it. Two is with creating the UITableView in a computed property. Both ways would give you the same result.


Initialize UITableView in ViewController via computer property.

We are going to set up a single app with a normal view controller. If you don’t know how to set up your project programmatically, please take a look at my past article or you can check out my youtube video. Once we have our application up and configured correctly, let’s jump over to our ViewController file.

The first option here is setting this up via a computed property.

class ViewController: UIViewController {

    let tableView: UITableView = {
        let tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        return tableView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        subviews()
        constraints()
    }
}

extension ViewController {
    func subviews() {
        view.addSubview(tableView)
    }

    func constraints() {
        NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: view.topAnchor),
            tableView.leftAnchor.constraint(equalTo: view.leftAnchor),
            tableView.rightAnchor.constraint(equalTo: view.rightAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
    }
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        return cell
    }


}
Enter fullscreen mode Exit fullscreen mode

Initialize UITableView in ViewController via a function.

The second option here is setting up UITableView with a function.

import UIKit

class ViewController: UIViewController {

    let tableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        subviews()
        constraints()
        setupTableView()
    }

    func setupTableView() {
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }
}

extension ViewController {
    func subviews() {
        view.addSubview(tableView)
    }

    func constraints() {
        NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: view.topAnchor),
            tableView.leftAnchor.constraint(equalTo: view.leftAnchor),
            tableView.rightAnchor.constraint(equalTo: view.rightAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
    }
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        return cell
    }


}
Enter fullscreen mode Exit fullscreen mode

Side note to remember that if you don’t introduce the “translatesAutoresizingMaskIntoConstraints” you will not see your UITableView populate on the screen! The definition for this wonderful long word — from Apple documentation is listed below.

If this property’s value is true, the system creates a set of constraints that duplicate the behavior specified by the view’s autoresizing mask. This also lets you modify the view’s size and location using the view’s frame, bounds, or center properties, allowing you to create a static, frame-based layout within Auto Layout.
Note that the autoresizing mask constraints fully specify the view’s size and position; therefore, you cannot add additional constraints to modify this size or position without introducing conflicts. If you want to use Auto Layout to dynamically calculate the size and position of your view, you must set this property to false, and then provide a non ambiguous, nonconflicting set of constraints for the view.
By default, the property is set to true for any view you programmatically create. If you add views in Interface Builder, the system automatically sets this property to false.


In Conclusion!

Now you can set up the UITableView just like normal if we were to do this in a storyboard file. When working with programmatic code, it’s about how you can customize it to your liking with animations, style, and being user friendly. Hope you guys enjoyed this little short article!

Top comments (0)