How to insert new cell into UITableView using Swift?

iOSiPhone/iPadMobile DevelopmentSwift

To insert a new cell into UITableView we'll first have to create a table view cell and then add it to the table view using Cell for row at method of Table view.

We can create a cell using Storyboard or by creating a nib of class UITableViewCell.

In the View controller drag and drop a table view and connect it's outlet to the ViewController class.

Let's create a cell in the table view we just created and create it's class, call it CustomCell, and assign the class to cell.

Give it an identifier "CustomCell"

Add a label in the cell and change it to "CustomCell", so that we can identify it, and place it in center vertically and horizontally.

Add the following code to our class

func numberOfSections(in tableView: UITableView) −> Int {
   return 1
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) −> Int {
   return 5
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) −> UITableViewCell {
   let cell = tblView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
   return cell

When we run this code this is how it will look on the device.

Published on 22-Jan-2019 17:14:29