How to Create UITableView in Swift in Just 15 Minutes by@khunshan

How to Create UITableView in Swift in Just 15 Minutes

UITableView is one of the most useful and commonly used view components in iOS development. It helps to display data in a scrollable list, such as a news feed, a reminder list, or any table of items. Apple allows you to create any variety of cells for one table view. To create a Table View you need to conform to its dataSource and delegate protocols. Implement the required protocol methods. Connect the tableView in code with a Table View in storyboard. Here is how you can do this and run a sample app in minutes.
image
Khunshan Ahmad Hacker Noon profile picture

Khunshan Ahmad

Writes about tech. Software engineer and digital marketer by profession. Peace.

UITableView is one of the most useful and commonly used view components in iOS development. It helps to display data in a scrollable list, such as a news feed, a reminders list, or any table of items.

UITableView contains UITableViewCells in it. To understand the relation between the two, think about an array and items. You can easily map items of an array to the cell in a table view. Additionally, you can create sections to map multiple arrays or a 2D array. 

Below is an example of UITableView usage. The native Settings app uses a table view with sections. The first section has 3 cells, whereas the second section has 1 cell. 

image

Usually, cells used in a table view have the same design and size, decreasing the overhead of redrawing the cells. However, Apple allows you to create any variety of cells for one table view.

UITableView Step 1: Open Xcode and Setup a Demo App

Open the Xcode app on your Mac to create a new project. Select the new App project from the popup and provide a nice title for the Product Name. For our example project, we are calling it ColorList. Your interface should be Storyboard and language set to Swift. 

image

Question: Why Storyboard? For ‘Interface’ we are using Storyboard, but if you are curious, the other option is SwiftUI. SwiftUI is the latest advancement to design UIs, but many developers believe it is not yet fully production-ready as iOS 14. 

Lastly, you can go the old way and create the whole UI in code as well. But I like to keep the view stuff separate instead of one fat controller.

Step 2: Add Table View to View Controller in Storyboard

Each new app comes with one view controller and a Storyboard. In simple words, every screen of the app is a UIViewController in code.

  1. Open Main.Storyboard file by clicking on it in the left pane.
  2. Select the xib showing for the view controller in the Storyboard. It’s the skeleton of an iPhone appearing in your Storyboard.
  3. Press the + button
  4. image
  5. Select UITableView
  6. image
  7. Drag and drop the Table View over Xib.
  8. Set zero for top, bottom, left, and right constraints. Press the ‘Add 4 Constraints’ button.
  9. image

That's it, your scrollable table view UI is ready to roll. You can add the constraints to make it stretch 100% in width and height.

image

Step 3: Connect Table View ‘Outlets’

The next step is to create the outlets in the view controller class. That way we can have access to table view in our controller to further add business and UI logic. There are multiple ways to do so. Here is the quickest one:

  1. Press the ‘option’ key on your Mac while your Storyboard is open. Keep holding that for step 2.
  2. Select the view controller file from the left pane. This will open the Storyboard and view controller files side-by-side.
  3. Press the ‘control’ key. Now while holding down the ‘control’ key, drag and drop the table view from Storyboard to the view controller.
  4. image
  5. Give the new var a name like tableView.
  6. image
  7. A tableView var is now created in the view controller. 
  8. image

Step 4: Setup Table View DataSource and Delegate

The table view has two weak objects inside the UITableView class to populate the data and manage delegation. Weak means the objects are not retained strongly.

The dataSource object is responsible for providing cells and their data for a table view. It is of ‘UITableViewDataSource?’ type.

The delegate object is of ‘UITableViewDelegate?’ type. It handles selection, deletion, header/footer, and other related actions.

To start, 

  1. Let's assign self to both of these properties.
  2.     override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
            
            tableView.delegate = self
            tableView.dataSource = self
        }
  3. We have to conform our view controller to dataSource and delegate protocol. This is because the delegate and dataSource objects allow assigning a class that must conform to their protocols. Let's do that.
  4. class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource 
  5. Xcode will ask you to add the required method stubs. These are the methods we have to provide bodies as they are required by dataSource and delegate objects.

    Here are the two method stubs added by Xcode. There are many other methods that you can use, check the documentation here.
  6.     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            //TODO: Return items count
            return 0
        }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            //TODO: Return cell
            return UITableViewCell()
        }
  7. The first numberOfRowsInSection- returns an Int. It is responsible for drawing the number of cells returned by this method.

    The other method cellForRowAt- returns an object of UITableViewCell type. This is where we can create a cell and pass data to it to configure its UI.
  8. We will create a dummy colors array. Let's name it ‘rainbow’.
  9. Return ‘rainbow.count’ for numberOfRowsInSection- method.
  10.     let rainbow: [UIColor] = [.red, .yellow, .green, .orange, .blue, .purple, .magenta]
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return rainbow.count
        }

  11. Now we create a new cell UI to return from cellForRowAt-. To do so, we will go to Storyboard where we already have our UIViewController view. Like #2, we will press the + button, select Table View Cell, drag and drop it over the Table View.
  12. image

  13. Select the UITableViewCell you just added. Then from the right pane select the Attributes Inspector tab. Add a string against the Identifier field. 
  14. In the cellForRowAt- method, dequeue the cell using tableView.dequeueReusableCell(withIdentifier: String, for: IndexPath) method.

    Here we will pass the Identifier to fetch the UI of the cell. In the next line, we are setting the cell's background color to the color object in the rainbow array.
  15. 
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "colorCell", for: indexPath)
            cell.backgroundColor = rainbow[indexPath.item]
            return cell
        }
  16. Run the project. You will see your array of colors showing up in the table view.
  17. image

What Else Can You Do With UITableView and UITableViewCell?

UITableView is your go-to UI view in most of the cases where scrolling behavior is desired. UITableView inherits from UIScrollView, just like UICollectionView - a UITableView like view where you can have cells both ways, i.e., horizontal and vertical.

The cell we are using is the default table view cell provided by iOS. You can create a custom class and, like the above steps, connect the UI and class. We will upload a How-To guide next week to create a custom-designed UITableViewCell.

The default cell can provide a title, background, and accessory view. We will add a title using defaultConfiguration- like this:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "colorCell", for: indexPath)
        cell.backgroundColor = rainbow[indexPath.item]
        
        //Default Content Configuration
        var content = cell.defaultContentConfiguration()
        content.text = rainbow[indexPath.item].accessibilityName.capitalized
        
        cell.contentConfiguration = content
        return cell
    }

That is what it will look like:

image

You can create different design cells in the same table view. By assigning different identifiers you can dequeue your required cell. The dequeueReusableCell method improves performance by creating only visible cells on the screen and a few more. By efficiently caching cells it can provide a fluid user experience.

That's how your whole code should look like. You can download the sample source code from here.

image

Let us know what you built with UITableView in our Hackernoon Community.

Khunshan Ahmad Hacker Noon profile picture
by Khunshan Ahmad @khunshan. Writes about tech. Software engineer and digital marketer by profession. Peace.Read my stories

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.