Easy TableView Setup Tutorial — Swift 4 (2024)

Hi everyone! Today, I will be showing you a step by step tutorial on how to setup a TableView programmatically as well as using the delegate and datasource protocols in Swift 4.2. I hope this tutorial serves as purposeful to you in your projects and let’s jump right in! 😃

Step 1: Create a ViewController.swift file

This will serve as the View Controller where we add our tableView subview and manage the UIKit app’s interface.

class ViewController: UIViewController {}

Step 2: In our ViewController class, instantiate a UITableView object

This is how we create a TableView object and set all the requirements for them within this scope.

Step 3: Setup the tableView and add constraints!

We add views and set constraints to them with the ViewDidLoad method. This method is called after the view has been loaded.
Instead of putting all the code inside viewDidLoad, we’re going to make this more readable by creating a function for setting up the tableView. 🙂

Once completed, try running the app and you should see the following!

Easy TableView Setup Tutorial — Swift 4 (2)

Step 4: Conform to UITableViewDelegate and UITableViewDataSource

According to Apples documentation — The delegate manages table row configuration and selection, row reordering, highlighting, accessory views, and editing operations.
While the data source provides information that UITableView needs to construct tables and manages the data model when rows of a table are inserted, deleted, or reordered.
Once we inherit from the delegate and datasource in our class, we then add the protocol stubs, and assign our tableView to the delegate and datasource methods. ( tableView.delegate = self )

1. We return 10 numbers of cells in the tableView
2. Create a tableViewCell to populate the screen.
Currently everything is configured through defaults, so we cannot change the views unless we create our own UITableViewCell class! 👇🏼👇🏼

Step 5: Create our own custom subclass of UITableViewCell

Note that this is of type UITableViewCell. According to apples documentation — This class includes properties and methods for setting and managing cell content and background (including text, images, and custom views), managing the cell selection and highlight state, managing accessory views, and initiating the editing of the cell contents.

Because UIView adopts the NSCoding protocol, it requires an init(coder:) initializer. And since we’re implementing init(style:reuseIdentifier:) , our class is no longer inheriting from the super initializers resulting in the implementation of the code on line 7 👆🏼

Step 6: Register the new cell class

Once we’ve added a TableViewCell class, we can now make our ViewController inherit this cell. And, in order to make that, we’ll need to do some small changes in setupTableView method and datasource protocol.

func setupTableView() {
...
tableview.register(ThirtyDayCell.self, forCellReuseIdentifier: "cellId")
...
}
...func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! ThirtyDayCell
...
}

The tableViewCells right now are very small, to offset this I will be adding a delegate method to increase the height for all cells.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
Easy TableView Setup Tutorial — Swift 4 (3)

Step 7: Add content to our ThirtyDayCell class

Easy TableView Setup Tutorial — Swift 4 (4)

With the above photo being what we need to end up with, we need to instantiate a UIView for the background color and then a UILabel to represent each day.

  • Instantiate the UIView and UILabel

In order to have this rounded cell look, we are going to add a UIView and that will represent the orange colored cells as you can see in the above picture!

  • Setup the UIView and add constraints!
    This step is similar to setting up the tableView but instead we set up the view in our override init method.
  • Setup the UILabel inside the UIView and add constraints!
Easy TableView Setup Tutorial — Swift 4 (5)

As you can notice, there is a small line that goes across the screen right under each of our cells. By default the tableView separator color is set to grey. We can change this easily in our instantiation of the tableView

let tableview: UITableView = {
...
tv.separatorColor = UIColor.white
return tv
}()

Step 8: Customize the data in each of our cells in this tableView(_:cellForRowAt:) method

Once we type cast the cell to ThirtyDayCell, we can access all the properties and methods within that class! And with this in mind, we’re going to change the dayLabel’s text.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! ThirtyDayCell
cell.backgroundColor = UIColor.white
cell.dayLabel.text = "Day \(indexPath.row+1)"

return cell
}

Easy TableView Setup Tutorial — Swift 4 (6)

Completed!!

Easy TableView Setup Tutorial — Swift 4 (2024)
Top Articles
You’re in a sustainability job interview. What are the most important things to say?
Morgan Silver Dollar Value: Silver Dollar Investment Guide
Asist Liberty
O'reilly's Auto Parts Closest To My Location
360 Training Alcohol Final Exam Answers
Comcast Xfinity Outage in Kipton, Ohio
Nation Hearing Near Me
Displays settings on Mac
Buckaroo Blog
Miami Valley Hospital Central Scheduling
Slope Unblocked Minecraft Game
Things To Do In Atlanta Tomorrow Night
Colts seventh rotation of thin secondary raises concerns on roster evaluation
Houses and Apartments For Rent in Maastricht
Aucklanders brace for gales, hail, cold temperatures, possible blackouts; snow falls in Chch
Grandview Outlet Westwood Ky
Alfie Liebel
Crawlers List Chicago
Fsga Golf
Optum Urgent Care - Nutley Photos
Www Va Lottery Com Result
Loslaten met de Sedona methode
Ontdek Pearson support voor digitaal testen en scoren
Vivaciousveteran
Tire Plus Hunters Creek
Times Narcos Lied To You About What Really Happened - Grunge
Tinyzonehd
Rek Funerals
Craigslist Boerne Tx
Meggen Nut
LG UN90 65" 4K Smart UHD TV - 65UN9000AUJ | LG CA
35 Boba Tea & Rolled Ice Cream Of Wesley Chapel
Slv Fed Routing Number
Cars And Trucks Facebook
Chase Bank Cerca De Mí
Steven Batash Md Pc Photos
Reborn Rich Ep 12 Eng Sub
Are you ready for some football? Zag Alum Justin Lange Forges Career in NFL
Barber Gym Quantico Hours
Сталь aisi 310s российский аналог
Gotrax Scooter Error Code E2
Arnesons Webcam
Mitchell Kronish Obituary
The Horn Of Plenty Figgerits
Reilly Auto Parts Store Hours
Youravon Com Mi Cuenta
Greatpeople.me Login Schedule
Erespassrider Ual
F9 2385
David Turner Evangelist Net Worth
The Significance Of The Haitian Revolution Was That It Weegy
Duffield Regional Jail Mugshots 2023
Latest Posts
Article information

Author: Lilliana Bartoletti

Last Updated:

Views: 5919

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lilliana Bartoletti

Birthday: 1999-11-18

Address: 58866 Tricia Spurs, North Melvinberg, HI 91346-3774

Phone: +50616620367928

Job: Real-Estate Liaison

Hobby: Graffiti, Astronomy, Handball, Magic, Origami, Fashion, Foreign language learning

Introduction: My name is Lilliana Bartoletti, I am a adventurous, pleasant, shiny, beautiful, handsome, zealous, tasty person who loves writing and wants to share my knowledge and understanding with you.