DEV Community

Cover image for iOS UITableView 100% Programmatically in Swift 4.0
Raja Tamil
Raja Tamil

Posted on • Edited on

iOS UITableView 100% Programmatically in Swift 4.0

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

STEP #1: Create a New Xcode Project
STEP #2: Get Rid of Storyboard
STEP #3: Set Root View Controller to the Window Object
STEP #4: Create Data Model Struct and Class Files - MVC
STEP #5: Add UITableView to the ContactViewController
STEP #6: Add AutoLayout Constraints to the UITableView
STEP #7: Implement UITableView DataSource Protocol Methods
STEP #8: Add UINavigationController to the View Controller
STEP #9: Create Custom UITableViewCell Programmatically
STEP #10: Implement UITableViewDelegate Protocol Method

STEP #1: Create a New Xcode Project

Create a project by opening Xcode and choose FileNewProject. 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 and unzip it, then drag them into the Assets.Xcassets file.

alt text

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.

Otherwise, keep reading.

Recommended
iOS 13 & Swift 5 – iOS App Development Bootcamp

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 InfoMain Interface and clear the Main text.

Delete the ViewController.swift file as well.

alt text

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

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

In Xcode, go to FileNewCocouTouch 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.

window = UIWindow(frame:UIScreen.main.bounds)
Enter fullscreen mode Exit fullscreen mode

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

window?.makeKeyAndVisible()
Enter fullscreen mode Exit fullscreen mode

Finally, assign ContactsViewController as a root controller of it.

 window?.rootViewController = ContactsViewController()
Enter fullscreen mode Exit fullscreen mode

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

view.backgroundColor = .red
Enter fullscreen mode Exit fullscreen mode

alt text

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.

struct Contact {     
  let name:String?     
  let jobTitle:String?     
  let country:String? 
}
Enter fullscreen mode Exit fullscreen mode

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.

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    
  } 
}
Enter fullscreen mode Exit fullscreen mode

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.

private let contacts = ContactAPI.getContacts() // model
Enter fullscreen mode Exit fullscreen mode

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

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

Top comments (0)