doyeona
Published in

doyeona

Few things that you must know about UITableView in Swift

TableView is the best way to display a list of data which contains header, footer, and section. It displays a single column of vertically scrolling content divided into rows.

📌 This post will be more about the concept of TableView rather than just making TableView

CollectionView vs TableView

Example of CollectionView vs TableView

Skip for the CollectionView for now 🤞🏻and Let’s talk about TableView in this post.

TableView is used literally everywhere! It’s the best way to display tons of data in list vertical format. Let’s look at the Contacts in iOS device. 👇🏻

Structure of the TableView (?)

So there’s a Header, Section and Footer in TableView and each Section has another header, footer and rows(cell) to display the data.

You probably know what is header and footer, so i will not gonna explain this part. It’s just the start and end of the table like a web page’s header and footer.

UITableViewCell

I think the most important thing to understand about tableView is the “REUSABLE CELL”.

Cell is the visual representation of a single row in a table view. Every table view must have at least one type of cell for displaying content. There are two types of cell.

  • Static cell: have a specific number of table sections and a rows set such as the contact lists as the image above. You can use the prototype cells and feed in a static NSArray where you would use storyboard and IB.
  • dynamic cell: You use prototype cells which means generate from the data, and can change during run time such as facebook’s news feed. Let’s say when we have tons of data that needs to be displayed in the tableView, that’s the time the cell is being reusable.

ReusableCell?

When the user scrolls the screen, the cell(data) goes up and at the end of the screen, there will be another cell(data) showing up and it will keep repeating that step again until there’s nothing more to show. Let’s look at the image below. That’s how I understand the logic of the reusable cell.

how does the reusable cell works
  1. To display the cell in collectionView or TableView, request cell instance to DataSource
  2. DataSource will check the queue whether there’s a (reusable)waiting cell or not from a given identifier. if yes, it will set the data in the cell to display. otherwise, it will create a new cell.
  3. If there’s any return cell from the DataSource, then display it to the TableView or CollectionView
  4. When the user scrolls, some of the cells that are not being displayed will again be put into the queue.
  5. repeat the step 1 to 5.

Sorry for the new word “DataSource”, it provides data to the UITableView or UICollectionView via protocol method by conforming. I will explain later!

Why does iOS use a reusable cell?

It’s because iOS has only limited memory usage. Therefore it’s a waste of memory if we load thousands of contents at once. That’s the reason why iOS uses a reusable cell queue mechanism to optimize memory usage.

Let’s back to TableView

There’s 2 ways to make tableView in iOS.

  1. Using TableView Controller
  2. Using View Controller
Pros and Cons of using TableViewController vs View Controller

So TableView need to conform the protocols to control the TableView such as UITableViewDataSource and UITableviewDelegate and as i said using TableView Controller, we don’t need to set up the delegate and datasource and it’s very convenient to start it but has limited flexibility so i guess we will deal with the tableView as a subclass of UIView most of the time.

TableView controller vs View Controller

❗️Note, When using the Static TableView cells, we have to use a TableViewController

UITableViewDataSource & UITableViewDelegate

🗣: Hey, you kept mentioning datasource and delegate above. What are those exactly?

We have to first understand the relationship between MVC patterns in UITableView. MVC is Apple’s recommended architecture pattern(not anymore, you will see Retired Document in apple’s document). Anyways, in architecture patterns including MVVM, the view model is responsible for exposing the data objects from the model to display

but think about the situation where the user touches the screen? The view has to do something with that action but cannot directly tell the controller that the user touched the screen such as enable the scroll? What kind of data? how many data..and more! Therefore we conform the protocols(= delegate) to connect between the view and the controller.

💁🏻‍♀️ Protocol is a set of methods that would be implemented by the class which conforms to that protocol, while, delegate is the reference to that class which conforms to that protocol. sources: here

Btw, you after you conforms that protocols, you see the error that saying below for UITableViewDataSource. While UITableViewDelegate doesn’t (methods are all optional!)

because UITableViewDataSource requires 2 methods which are

  1. numberOfRowsInSection: returns how many number of rows
  2. cellForRowAt: represent each cell

Let’s make the TableView!

As i said there’s 2 ways of making TableView, and I’ll be making Tableview as a subview of UIView.

1️⃣ Creating the Table View inside the View Controller’s View and cell for the Table View

Simply drag and drop

2️⃣ Connect the outlet to ViewController and conforms the protocols. Since we need the protocols and get interactions from the TableView, we have to notify ViewController class by writing tableView.dataSource = self , tableView.delegate = self

3️⃣ Let’s set up some data in an array just to see some samples!

let arr = ["A","B","C","D","E","F"]

4️⃣ Let’s tell how many rows we’ve got to UITableViewDataSource! [REQUIRED]

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {     return arr.count
}

5️⃣ Let’s tell how the cell should look like such as text and stuff.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {     let cell: UITableViewCell =         self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)cell.textLabel?.text = arr[indexPath.row]return cell
}

btw, you can make the class for Cell to control the properties. If you have some labels, images, and other stuff in your cell to display. then don’t forget to downcast the class to access it. something like this: guard let cell = self.tableView.dequeueReusableCell(withIdentifier: “cell”, for: indexPath) as? TableViewCell else { return TableViewCell()}

hold on.. What is the withIdentifier and indexPath.row?

  • withIdentifier : As i mentioned identifier while explaining the ReusableCell. if not, ctrl + f and search identifier. We need that identifier to check if there’s a waiting cell within that identifier in the queue. How to get the identifier?
set the identifier in cell
  • indexPath.row : data should be different displaying in each cell. and how to identify them? it’s by indexPath.row. That’s why it’s able to display each data in the array in each cell. Try to print out the indexPath and you’ll see something like the image below.
print(indexPath)

that’s why when you wanna display the the data in each rows, you should access it by indexPath.row😴

when you run the code,

You will see the data in an array that is being displayed in each cell.

This is the end of the post! Thank you for reading. Please correct me if there’s something wrong or improve on my explanation!

Actually there are many more things to study about the tableView such as sections, headers, footers,,, and more. I’m sure those are easily found on google and explained nicely. For me, making your own project is important, but studying the concept or to know the basic things of it is a must to get yourself better in expanding your knowledge.

--

--

--

Daily study logs about iOS development will be updated. Any recommendations or discussions are always welcome

Recommended from Medium

How to test and debug mobile push notifications with the Sendbird tester tool

Fledge: A CI/CD Tool For Flutter

How to Run Your First Hello World App on Your iPhone

An Overview of Built-In SwiftUI Views

Phone

UserInterfaceLevel, the future of floating apps

iOS interview question 2020

SWIFTip#3: Casual insight of the week

Some tips in Swift

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Doyeon

Doyeon

Hey! I am currently studying iOS by myself, and wanna be a cool app developer 🕶 please correct me if i’m wrong or if there’s any thing that you wanna share😊✌️

More from Medium

GCD: DispatchSource and Target Queue Hierarchy

Odometer reading input in Swift

Making a Cocoapod in Swift with an Objective-C .framework dependency

Swift Package Manager (SwiftPM/SPM) — Creating and Publishing one