Swift- Create a Custom Tableview in iOS

UITableView is one of the most important UserInterface in iOS. It's not difficult to implement UITableView, almost every app uses its functionality. If one wants to customize and add additional features to tableview cell, one might need to create Custom TableViewCell Class.

Here is the end result what we are going to build.


Creating an UITableView

  There are two ways of creating UITableView, either you can use it programmatically or it can be done using interface builder. The second approach is the most common one, so will do in this way.

Step 1 - Create XCode Project 

      Open Xcode and create a new project by selecting Single View App from XCode IDE, and name the project as customTableView


Step 2 - Create a Model
Click File from Menu, and select Swift file i.e., File -> New -> File -> Swift File and name the file as CustomTableData.




          We create this model to fetch the data into your tableview. Model consisting of properties which are going to be used in our custom-tableview-cell.  After creating the CustomTableData file add the below code in the newly created swift file.

class CustomTableData {
    
    var imageName: String?
    var titleName: String?
    
    
    init(imageName:String?, titleName: String?) {
        self.imageName = imageName
        self.titleName = titleName
    }

}
   

Step 3 - Create CustomTableViewCell

            Next step is to create a CustomTableViewCell including xib. Click File from Menu, and select Cocoa Touch Class i.e., File -> New -> File -> Cocoa Touch Class and name the file as CustomTableViewCell and UITableViewCell as it subclass




Tick "Also Create XIB file" option, which automatically creates XIB File to your TableViewCell

       Add UIImageView and UILabel Outlets in the CustomTableViewCell Class
           
                   @IBOutlet weak var leftImage: UIImageView!
                   @IBOutlet weak var titleLabel: UILabel!
    
    Click on CustomTableViewCell.xib to set outlets for image and label and a suitable name to register cell identifier




CustomTableCellIdentifier is the name of this identifier

      Finally the CustomTableViewCell class implementation looks like below

class CustomTableViewCell: UITableViewCell {

    @IBOutlet weak var leftImage: UIImageView! {
        didSet {
            leftImage.layer.cornerRadius = leftImage.bounds.size.width * 0.5
        }
    }
    
    @IBOutlet weak var titleLabel: UILabel! {
        didSet {
            
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    func setupData(imageName: UIImage, titleName: String) {
        leftImage.image = imageName
        titleLabel.text = titleName
    }

}

Step 4 - Create TableViewController

       ViewController.swift is the default file created with your project, here our actual work goes.

Create tableView IBOutlet

  • @IBOutlet weak var customTableView: UITableView!
Register tableview with the custom table view cell identifier

           // Here customTableView is the name of the tableview
  • customTableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "customTableCellIdentifier")

Setup TableView in the storyboard

Open Main.storyboard, drag and drop UITableView to the ViewController from Library and set the customTableView Outlet to the UITableView as shown below



Next Create a function which loads the data to the CustomTableData, and call this function from ViewDidLoad

    func loadDatatoDataList() {
        customDataList.append(CustomTableData(imageName: "jasmine.jpg", titleName: "Jasmine"))
        customDataList.append(CustomTableData(imageName: "lilly.jpg", titleName: "Lilly"))
        customDataList.append(CustomTableData(imageName: "lotus.jpg", titleName: "Lotus"))
        customDataList.append(CustomTableData(imageName: "marigold.jpg", titleName: "Marigold"))
        customDataList.append(CustomTableData(imageName: "Rose.jpg", titleName: "Rose"))

    }


Add Delegate and DataSource methods in the ViewController.

It tells the datasource to return the number of rows in a given section fo a UITableView

func tableView(_ tableView: UITableView, 
numberOfRowsInSection section: Int) -> Int


Asks the datasource for a cell to insert in a particular location of a tableview








func tableView(_ tableView: UITableView, 
  cellForRowAt indexPath: IndexPath) -> UITableViewCell


Finally the overall implementation looks like below

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var customTableView: UITableView!
    var customDataList = [CustomTableData]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        loadDatatoDataList()
        customTableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "customTableCellIdentifier")
    }
    
    func loadDatatoDataList() {
        customDataList.append(CustomTableData(imageName: "jasmine.jpg", titleName: "Jasmine"))
        customDataList.append(CustomTableData(imageName: "lilly.jpg", titleName: "Lilly"))
        customDataList.append(CustomTableData(imageName: "lotus.jpg", titleName: "Lotus"))
        customDataList.append(CustomTableData(imageName: "marigold.jpg", titleName: "Marigold"))
        customDataList.append(CustomTableData(imageName: "Rose.jpg", titleName: "Rose"))
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return customDataList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "customTableCellIdentifier", for: indexPath) as? CustomTableViewCell else {
                        return UITableViewCell()
                    }
        
        let tableData: CustomTableData
        tableData = customDataList[indexPath.row]
        cell.setupData(imageName: UIImage(named: tableData.imageName!)!, titleName: tableData.titleName!)
        return cell
    }
}



Now click on run button in Xcode, and the result appears as below

                    

















Comments

Post a comment