Customize UITableViewCell for UITableView.

One of the important components of UIKit framework is UITableView. A table view displays a list of items in a single column. The main purpose of writing this blog post is to develop custom cells in UITableView.

Step 1: Create Xcode Project

Now, create a new Xcode Project. This project will contain a single view controller, which is our main view controller.

Step 2 : Design ViewController

Got to Main.storyboard and drag UITabelView into the ViewController and set the width & height of UIView Controller to View Controller.

 

Now embed this table view controller to UINavigationController by selecting Editor (form top menu) >> Embed In >> Navigation Controller. Double click on the title bar of the UITableViewController and name it as Example.

Step 3 : Create UITableView outlet in your ViewController.swift file.

To create outlets, ensure that your scene’s storyboard is displayed by selecting it in the Project navigator. Next, select the Assistant editor button () on the Xcode toolbar (or select View > Assistant Editor > Show Assistant Editor). Xcode’s Editor area splits and the file ViewController.swift  is displayed to the right of the storyboard. By default, when viewing a storyboard, the Assistant editor shows the corresponding view controller’s source code. However, by clicking Automatic in the jump bar at the top of the Assistant editor, you can select from options for previewing the UI for different device sizes and orientations, previewing localised versions of the UI or viewing other files that you’d like to view side-by-side with the content currently displayed in the editor.

You’ll now create an outlet for the blue UITableVIew.  Outlets are declared as properties of a view controller class. To create the outlet

  1. Control drag from the blue UITableView  in ViewController.swift  and release. This displays a popover for configuring the outlet .
  2. In the popover, ensure that Outlet is selected for the Connection type, specify the name tableView for the outlet’s Name and click Connect.

Xcode inserts the following property declaration in class ViewController:

@IBOutlet weak var tableView: UITableView!

 

Step : 6 Create Array object.

Now, you have to create an Array object which is basically holding the data set  of Table items.

var dataList  = [MyDataSet]()

Copy and paste  this line of code below the TableView outlet. In other words, declare dataList object as a global variable of ViewController class. this , dataList , is an array of MyDataSet class.

Create a new swift file and name it MyDataSet. Now, copy and paste the below code in this file. This is class which contains a title and a description variable.

class MyDataSet {
    var title : String
    var description : String

    init(title : String , description : String) {
        self.title = title;
        self.description = description
    }
}

Step : 5 Inherit UITableView Properties.

Add below code at the bottom of your ViewController.

// Make TableView DataSource.
extension  ViewController : UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1;
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     // will return UITableViewCell.
    }    
}

// Make TableView Delegate.

extension ViewController : UITableViewDelegate {

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }    

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

    }

}

Step : 6 Create UITabelViewCell file.

Create a new Cocoa Class Touch file and name it TableViewCell  this should be subclass of UITableViewCell and checked the ‘Also create xib file’ check box.

This will generate two file one TableViewCell.swift and other one is .xib file with the same name.

Step 7 : Design Cell UI.

Its time to design the custom cell. Go to the TableViewCell.xib and drag the UILabel into the content view cell. I am dragging two UILabels one below another.

Now create the outlets of both Label in its Assistant class and name them title and desp respectively

 

Step 8: Cell Identify ID

You need to create a Identify ID of your custom table view cell, so that , you can register your cell to TableView. This ID should be unique.

Go to the CustomTableViewCell.swift and follow the step which is mentioned in below image.

Note: Try to create ID same as the class name. I called it CustomTableViewCell.

 

Step 9 : Use Cell identifier in main ViewController to register Cell (using UINib).

In your ViewController.swift, create a global string variable. The value of this variable should be same as Identity cell.

    var identifier : String  = "CustomTableViewCell";

In your viewDidLoad() function, write below lines to register the custom cell with table view.

// Note : the value of nibName is Nib File Name (CustomTableViewCell.xib) 
let nib :UINib = UINib(nibName: "CustomTableViewCell", bundle: nil);
self.tableView.register(nib, forCellReuseIdentifier: identifier)

The Last thing you need to do is mapping the delegate and datasource of your ViewController class to the tableView instance. To map , write below lines in your  viewDidLoad() function.

self.tableView.delegate = self;
self.tableView.dataSource = self;

Step 10 : Init custom Cell 

// Make TableView DataSource.
extension  ViewController : UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {\
        return 1;
    }
   
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return dataList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier,for:indexPath) as! CustomTableViewCell //
        cell.title.text  = dataList[indexPath.row].title
        cell.desp.text = dataList[indexPath.row].description
        return cell;

    }
  }

Step 11 : Insert new rows

let count : Int = dataList.count;
self.dataList.insert(MyDataSet.init(title: "Row Title", description: "Row Despricption"), at: count);
let index = IndexPath(row : count , section: 0) ;
self.tableView.insertRows(at: [index], with: .automatic);

After doing all stuffs , the final code in your ViewController should be:

class ViewController: UIViewController {
    var identifier : String  = "CustomTableViewCell";
    @IBOutlet weak var tableView: UITableView!
    var dataList  = [MyDataSet]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let nib :UINib = UINib(nibName: "CustomTableViewCell", bundle: nil);
        self.tableView.register(nib, forCellReuseIdentifier: identifier)
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
  
        addRow();

    }

    func addRow()  {
      let count : Int = dataList.count;
      self.dataList.insert(MyDataSet.init(title: "Hello", description: "Hello Desp"), at: count);
      let index = IndexPath(row : count , section: 0) ;
      self.tableView.insertRows(at: [index], with: .automatic);
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

// Make TableView DataSource.

extension  ViewController : UITableViewDataSource{

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return dataList.count
    }
   
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier,for:indexPath) as! CustomTableViewCell
        cell.title.text  = dataList[indexPath.row].title
        cell.desp.text = dataList[indexPath.row].description
        return cell;
    }
}

// Make TableView Delegate.

extension ViewController : UITableViewDelegate {

   func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100;
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("Row Selected : \(indexPath.row). Perform your selection action here.")
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        print("Row deSelected : \(indexPath.row)")
    }

}

Posted

in

,

by

Recent Post

  • Generative AI in Hospitality: Integration, Use Cases, Challenges, and Future Outlook

    Generative AI is revolutionizing the hospitality industry, redefining guest experiences, and streamlining operations with intelligent automation. According to market research, the generative AI market in the hospitality sector was valued at USD 16.3 billion in 2023 and is projected to skyrocket to USD 439 billion by 2033, reflecting an impressive CAGR of 40.2% from 2024 […]

  • Generative AI for Contract Management: Overview, Use Cases, Implementation Strategies, and Future Trends

    Effective contract management is a cornerstone of business success, ensuring compliance, operational efficiency, and seamless negotiations. Yet, managing complex agreements across departments often proves daunting, particularly for large organizations. The TalkTo Application, a generative AI-powered platform, redefines contract management by automating and optimizing critical processes, enabling businesses to reduce operational friction and improve financial outcomes. […]

  • Generative AI in customer service: Integration approaches, use cases, best practices, and future outlook

    Introduction The rise of generative AI is revolutionizing customer service, heralding a new era of intelligent, responsive, and personalized customer interactions. As businesses strive to meet evolving customer expectations, these advanced technologies are becoming indispensable for creating dynamic and meaningful engagement. But what does this shift mean for the future of customer relationships? Generative AI […]

  • Generative AI in corporate accounting: Integration, use cases, challenges, ROI evaluation, and future outlook

    Overview Corporate accounting is fundamental to ensuring an organization’s financial stability and strategic growth. As the cornerstone of financial reporting and decision-making, it upholds transparency and accountability in business operations. However, technological advancements, particularly the emergence of generative AI, are redefining the field. By automating repetitive tasks and amplifying data-driven insights, generative AI in corporate […]

  • Generative AI in HR Operations: Overview, Use Cases, Challenges, and Future Trends

    Overview Imagine a workplace where HR tasks aren’t bogged down by endless paperwork or repetitive chores, but instead powered by intelligent systems that think, create, and adapt—welcome to the world of GenAI. Generative AI in HR operations offers a perfect blend of efficiency, personalization, and strategic insight that transforms how organizations interact with their talent. […]

  • Generative AI in Sales: Implementation Approaches, Use Cases, Challenges, Best Practices, and Future Trends

    The world of sales is evolving at lightning speed. Today’s sales teams are not just tasked with meeting ambitious quotas but must also navigate a maze of complex buyer journeys and ever-rising customer expectations. Despite relying on advanced CRM systems and various sales tools, many teams remain bogged down by repetitive administrative tasks, a lack […]

Click to Copy