Reviewing the basics : The simple UIKit TableView in Swift

Jason Haque
2 min readMay 9, 2021

--

Tableviews have always been an integral part of modern iOS app development. Even though the focus seems to be on SwiftUI these days we are gonna be using UIKit for this basic writeup.

So first thing is first ,open Xcode and click on create a new Xcode project

Click Next and go to the next page to name your Project. Make sure to select the interface as Storyboard and lifecycle S UIKit App Delegate

Click next and your project will be created. Now on to the coding part .

Go to the ViewController.swift file and let’s get started.

first to setup the table view

private let basicTableView : UITableView = {let table = UITableView()//register a cell to the tabletable.register(UITableViewCell.self, forCellReuseIdentifier: “cell”)return table}()

what this basically does is creates the tableview and registers a cell to it . Note the identifier of the cell here . The cell we register here is a kind of like a blueprint , the tableview will build off of the layout of this cell . This identifier will be pretty important to identify the cell from the delegate functions. speaking of which we will now add the tableview to the viewDidLoad() function and set some attributes of it.

view.addSubview(basicTableView)//setting the datasource and delegate for the table viewbasicTableView.dataSource = selfbasicTableView.delegate = self

next we will layout the subviews of this table view using this function

override func viewDidLayoutSubviews() {super.viewDidLayoutSubviews()basicTableView.frame = view.bounds}

All we have left are to implement two functions in a separate extension (you know cause clean code is good code )

extension ViewController : UITableViewDelegate , UITableViewDataSource{//returns the number of rows in a tablefunc tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return 10}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {let cell = basicTableView.dequeueReusableCell(withIdentifier: “cell”, for: indexPath)cell.textLabel?.text = “Hello there \(indexPath.row+1)”return cell}}

And then when you run the code you will see the fruits of your labour . A simple basic tableView like the one below

That’s it for this one . To get the full code for this beginner project visit https://github.com/open-source-extra/ios-how-to and follow me for more future content

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Jason Haque
Jason Haque

Written by Jason Haque

Tech Enthusiast, Software Engineer trying to build his own company

No responses yet

Write a response