iOS UITableView 100% Programmatically in Swift 4.0
Tags: ios, swift, programming
Published: 2021-05-31 13:52:49

In this swift tutorial, you are going to learn how to build a custom UITableView programmatically using Swift 4.0 with STEP by STEP instructions.

Along the way, I am going to be showing you how to create a custom UITableViewCell programmatically from scratch as well.

If you are new to building programmatic UI in Xcode, take a look at this [article](https://softauthor.com/ios-stop-using-storyboard-start-building-programmatic-ui/#get-rid-of-storyboard-xcode-project) which covers how to create a simple login screen programmatically.

At the end of this guide, you will be able to build a simple contacts app like the image below.

Sounds interesting! Let’s get started! 🚀

![alt text](https://softauthor.com/wp-content/uploads/2018/04/uitableview-programmatically-in-swift.gif)

STEP #1: [Create a New Xcode Project](https://softauthor.com/ios-uitableview-programmatically-in-swift/#create-a-new-xcode-project)
STEP #2: [Get Rid of Storyboard](https://softauthor.com/ios-uitableview-programmatically-in-swift/#get-rid-of-storyboard)
STEP #3: [Set Root View Controller to the Window Object](https://softauthor.com/ios-uitableview-programmatically-in-swift/#set-root-view-controller-to-the-window-object)
STEP #4: [Create Data Model Struct and Class Files - MVC](https://softauthor.com/ios-uitableview-programmatically-in-swift/#create-model-struct-and-class-files)
STEP #5: [Add UITableView to the ContactViewController](https://softauthor.com/ios-uitableview-programmatically-in-swift/#add-uitableview-to-the-viewcontroller)
STEP #6: [Add AutoLayout Constraints to the UITableView](https://softauthor.com/ios-uitableview-programmatically-in-swift/#add-autolayout-constraints-to-the-uitableview)
STEP #7: [Implement UITableView DataSource Protocol Methods](https://softauthor.com/ios-uitableview-programmatically-in-swift/#implement-uitableviewdatasource-protocol-methods)
STEP #8: [Add UINavigationController to the View Controller](https://softauthor.com/ios-uitableview-programmatically-in-swift/#add-uinavigationcontroller-to-the-view)
STEP #9: [Create Custom UITableViewCell Programmatically](https://softauthor.com/ios-uitableview-programmatically-in-swift/#custom-uitableviewcell-programmatically)
STEP #10: [Implement UITableViewDelegate Protocol Method](https://softauthor.com/ios-uitableview-programmatically-in-swift/#implement-uitableviewdelegate-protocol-methods)


###STEP #1: Create a New Xcode Project

Create a project by opening Xcode and choose **File** → **New** → **Project**. Then, choose a single view application and name it **contactsapp** and leave all other settings as is.

Once the project is created, download the asset files in [here](https://drive.google.com/file/d/1Or4sqF3lcswShclKtnmFkh7Rlloavf7H/view) and unzip it, then drag them into the **Assets.Xcassets** file.

![alt text](https://softauthor.com/wp-content/uploads/2018/04/add-assets-to-xcassets.gif)

As I am going to build this app 100% programmatically, **Main.Storyboard** is not needed for this project.

>*If you want to keep the Main.Storyboard, that’s okay, you can still follow along. In that case, you can skip the next two sections and jump right into STEP #4: [Create Data Model Struct and Class Files - MVC](https://softauthor.com/ios-uitableview-programmatically-in-swift/#create-model-struct-and-class-files).*

Otherwise, keep reading.

>✅ *Recommended*
>[*iOS 13 & Swift 5 – iOS App Development Bootcamp*](https://www.udemy.com/course/ios-13-app-development-bootcamp/?ranMID=39197&ranEAID=nsrC6aUWa3g&ranSiteID=nsrC6aUWa3g-p7gbsMjYNTFn9jPU.myrXg&LSNPUBID=nsrC6aUWa3g&utm_source=aff-campaign&utm_medium=udemyads)

###STEP #2: Get Rid of Storyboard

Delete **Main.Storyboard**.

Get rid of its reference as well by going to the top level of the project folder → **General** Tab→ **Deployment Info** → **Main Interface** and clear the **Main** text.

Delete the **ViewController.swift** file as well.

![alt text](https://softauthor.com/wp-content/uploads/2018/04/get-rid-of-storyboard.gif)

At this stage, the Xcode does not have an entry point, meaning the project does not have a **root view controller** that it points to, which will normally appear first followed by the splash screen when you run the app.

>*Recommended*
{% youtube qjDexTII42Y %}

###STEP #3: Set Root View Controller to the Window Object

In Xcode, go to **File** → **New**→ **CocouTouch** Class → name it **ContactsViewController** and make it a subclass of UIViewController.

>*Note: This class could be a subclass of UITableViewController instead of UIViewController that will hook everything to the TableView for us. However, doing it manually will help you to understand the steps involved in the same process.*

Go to **AppDelegate.swift** file → **didFinishLaunchingWithOptions()** method.

Create a window object by instantiating **UIWindow()** constructor and make it the screen size of the device using **UIScreen.main.bounds**.

```Swift
window = UIWindow(frame:UIScreen.main.bounds)
```

Once the window object is created, make it visible by invoking **makeKeyAndVisible()** method on it.

```Swift
window?.makeKeyAndVisible()
```

Finally, assign **ContactsViewController** as a root controller of it.

```Swift
 window?.rootViewController = ContactsViewController()
```

When adding the root view controller manually, Xcode will set its background colour to black by default. Let’s change it so that it’s working properly.

Go to **ContactsViewController.swift** file → **ViewDidLoad()** method

```Swift
view.backgroundColor = .red
```

![alt text](https://softauthor.com/wp-content/uploads/2018/04/Screen-Shot-2018-04-29-at-9.51.33-AM.png)

Let’s follow the MVC [Model-View-Controller] pattern of organizing files for our contacts app.

###STEP #4: Create Data Model Struct and Class Files

I am going to create two files as part of the model for our app, which are **Contact.swift** and **ContactAPI.swift**.

Go ahead and create the **contact.swift** file and choose the **Swift File** option as it will be a UI Independent Class.

This file contains a simple Contact Struct that will have a few properties in it based on the final table view cell image below.

- Profile Image
- Name
- Job Title
- Country

I will be setting the profile image reference names to the same as names so that I do not have to create a property for the profile image.

```Swift
struct Contact {     
  let name:String?     
  let jobTitle:String?     
  let country:String? 
}
```

>*Note: Make all the properties optional so that you can safely unwrap them using if let when they are nil rather than using the force unwrapping operator (!).*

Now, create a second file which is **ContactAPI.swift**.

In real-world applications, all the API calls code would go there. For simplicity sake, I will be adding some dummy data so that I do not have to make an HTTP request as it’s out of our scope topic.

Create a static method called **getContacts()** inside the **ContactAPI** class which is responsible to get all of the contacts data.

```Swift
class ContactAPI {     
 static func getContacts() -> [Contact]{         
   let contacts = [             
     Contact(name: "Kelly Goodwin", jobTitle: "Designer", country: "bo"),             
     Contact(name: "Mohammad Hussain", jobTitle: "SEO Specialist", country: "be"),             
     Contact(name: "John Young", jobTitle: "Interactive Designer", country: "af"),             
     Contact(name: "Tamilarasi Mohan", jobTitle: "Architect", country: "al"),             
     Contact(name: "Kim Yu", jobTitle: "Economist", country: "br"),            
     Contact(name: "Derek Fowler", jobTitle: "Web Strategist", country: "ar"),            
     Contact(name: "Shreya Nithin", jobTitle: "Product Designer", country: "az"),            
     Contact(name: "Emily Adams", jobTitle: "Editor", country: "bo"),             
     Contact(name: "Aabidah Amal", jobTitle: "Creative Director", country: "au")
    ]         
   return contacts    
  } 
}
```

As you can see in the above code, I have created an array named contacts and added a few contact objects instantiated with some data and returned it.

Create a property called **contacts** and assign the value, which would be an array of contact objects, by invoking **getContacts()** method on ContactAPI, like the code below.

```Swift
private let contacts = ContactAPI.getContacts() // model
```

>*Note: As you can see, I use static keyword in front of the getContacts() methods when declaring it so that I do not have to instantiate ContactAPI class to invoke getContacts() method.*

Pretty straight forward!

>✅ *Recommended*
>[*The Complete iOS 11 & Swift Developer Course – Build 20 Apps*](https://www.udemy.com/course/complete-ios-11-developer-course/?ranMID=39197&ranEAID=nsrC6aUWa3g&ranSiteID=nsrC6aUWa3g-gayFYDN5PftDd7bClq2QGw&utm_source=aff-campaign&LSNPUBID=nsrC6aUWa3g&utm_medium=udemyads)

###STEP #5: Add UITableView to the ContactsViewController

Go to **contactsViewController.swift** → Create a property called **contactsTableViewassign** to a table view object by instantiating **UITableView()** constructor.

[Continue Reading...](https://softauthor.com/ios-uitableview-programmatically-in-swift/#get-rid-of-storyboard)