How to UITableView Programmatically with Swift

Yoel Lev
2 min readApr 20, 2018

--

In this tutorial I will show you how to create a basic UITableView using code only, no Storyboard, no xib, just Code.

Lets dive in…

  1. Open Xcode and create a new Single View App project, give it a name TableView, click next, save it somewhere and click Create.
  2. Delete the ViewController.swift in the Xcode Navigator.
  3. Click on the Project name in the Navigator, go to the General Tab, under Deployment Info, delete the “Main” Storybaord, it should stay empty.
  4. Create a new Swift file and name it TableViewExample
  5. Add the following code to the TableViewExample.swift file you just created.
import UIKitclass TableViewExample: UITableViewController {

let cellId = “cellId”

override func viewDidLoad() {
super.viewDidLoad()

setupTableView()
}

func setupTableView(){
//Registers a class for use in creating new table cells.
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)

}

}

Open AppDelegate.swift, in the didFinishLaunchingWithOptions method add the following code.

  window = UIWindow()
window?.makeKeyAndVisible()
window?.rootViewController = TableViewExample()

Now lets add those UITableView Delegate Methods.

open TableViewExample.swift and at the end of the file add the following extension.

extension TableViewExample {

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}


override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
cell.textLabel?.text = "Hello, World"

return cell
}}

Build and run.

Other Articles:

Diffable Data Sources & Compositional Layouts part 1

Diffable Data Sources & Compositional Layouts part 2

Sharing a Core Data Model

Where you can find me

Twitter

Website

Github

Download Project

--

--

Yoel Lev

Senior iOS Developer @ TinyTap, Creator of Wavez. #wavez_app