12.3. Setting up the ViewController with TableView

Now we will patch up the view to the controller. Let's open up MainScreen -> ViewController.swift file, and add the following code there:

//
//  ViewController.swift
//  App12
//
//  Created by Sakib Miazi on 6/1/23.
//

import UIKit

class ViewController: UIViewController {

    let mainScreen = MainScreenView()
    
    override func loadView() {
        view = mainScreen
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "My Contacts"
        
        //MARK: Make the titles look large...
        navigationController?.navigationBar.prefersLargeTitles = true
        
        //MARK: Put the floating button above all the views...
        view.bringSubviewToFront(mainScreen.floatingButtonAddContact)
    }
}

In the above code,

  • On line 21, we set the title to "My Contacts."

  • On line 24, we tell the navigation controller that we prefer large titles, not the default smaller ones.

  • On line 27, we bring the floating button on top of all the views.

If you run the app now, it'd look like this:

Patching the Table View

We need to create a data model for the contacts to display them. Let's create a data model (a struct) Contact in Data Models -> Contact.swift file.

Create a new Group named 'Data Models' and add Contact.swift file inside.

Now let's open the ViewController.swift file, and add an array of Contacts for the table view.

Adopting TableView protocols

Let's separate the adoption of the protocols from ViewController.swift. So, let's create a file Main Screen -> ContactsTableViewManager.swift and write the following code there:

Here we are extending ViewController and adopting UITableViewDelegate and UITableViewDataSource protocols in a separate file.

Then open up ViewController.swift again, and patch the delegate and data source of the table view in ViewController.

Last updated

Was this helpful?