Article by: Manish Methani
Last Updated: October 3, 2021 at 2:04pm IST
Custom Cell means you can create your own cell and customize it in your own way. You can add a button, profile image, etc as per your need. We had covered the basic UITableView cell in the previous tutorial. you can just define the basic default cell for your tableView. But to customize it for user-friendly UI you need to define the custom cell.
Open Xcode,
Goto File > New > Project > Single View Application > Enter Project Name (eg :- FirstProjectViewController) and Select Language as Swift > Done.
Now you can see a file on the left navigation Menu of Xcode named, ViewController.swift
We start first with AppDelegate.swift File. Copy and paste this code in the didFinishLaunchingWithOptions method (the very first method you can see in Appdelegate.swift)
import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.main.bounds) let mainController = ViewController() as UIViewController let navigationController = UINavigationController(rootViewController: mainController) navigationController.navigationBar.isTranslucent = false self.window?.rootViewController = navigationController self.window?.makeKeyAndVisible() return true }
AppDelegate is the file that is called first when your App Starts. There are many ViewControllers added to your file. So How our App knows which one to start first? So in the didFinishLaunchingApplications, we told our code to begin with the ViewController file.
UINavigationController is mostly what you see in every App. This is a header with teal color as you see in the Final Output Image. Word itself tells its mean. It Controls all the navigation.
self.window?.rootViewController = navigationController
In this way, you can set Root View Controller. In our case we want ViewController.swift file to be the first one to start.
ViewController.swift file looks like this. You might see an error of CustomContactsTableViewCell we will cover this ...Just go step by step to understand the functionality. :-
import UIKit private let myArray: NSMutableArray = ["C","Objective-C","Swift"] var myTableView = UITableView() class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.navigationItem.title = "Programming Languages" self.navigationController?.navigationBar.barTintColor = UIColor.init(red: 0/255.0, green: 128/255.0, blue: 128/255.0, alpha: 1.0) self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] self.navigationController?.navigationBar.tintColor = UIColor.white myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: self.view.frame.height - 60)) myTableView.register(CustomContactsTableViewCell.self, forCellReuseIdentifier: "cell") myTableView.dataSource = self myTableView.delegate = self self.view.addSubview(myTableView) myTableView.backgroundColor = UIColor.clear // myTableView.separatorStyle = UITableViewCellSeparatorStyle.none } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 0 // you should probably return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return myArray.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("Num: (indexPath.row)") print("Value: (myArray[indexPath.row])") } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomContactsTableViewCell cell.backgroundColor = UIColor.clear cell.nameLabel.text = "(myArray [indexPath.row])" return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } }
A short description of an Example:
We had given a backgroundColor to NavigationBar, Added a Programming Languages title, and given a White text Color to Title.
Here, viewDidLoad() method is called first. In this method, we initialized a UITableView.
myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: self.view.frame.height - 60))
Then, we registered a data source and delegate methods of TableView. We have to register these methods to implement its delegate methods.
myTableView.dataSource = self myTableView.delegate = self
Then you have to register the forCellReuseIdentifier and give it some name which you use in the cellForRowAtIndexPath method of UITableView.
myTableView.register(CustomContactsTableViewCell.self, forCellReuseIdentifier: "cell")
The last line adds tableViewTutorialsTitle as a subView inside view.
self.view.addSubview(myTableView)
In numberOfRowsInSection we are going to use the count of elements in our NSMutableArray to tell the tableView how many rows to create:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return myArray.count }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomContactsTableViewCell cell.backgroundColor = UIColor.clear cell.nameLabel.text = "(myArray [indexPath.row])" return cell }
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
This method is used to set the height of a row.
Open Xcode Goto File > New >File > Coca Touch Class > Next > Enter File Name (CustomContactsTableViewCell) and Select Language as Swift > Done.
Now you can see a file on the left navigation Menu of Xcode named, CustomContactsTableViewCellroller.swift Paste code inside CustomContactsTableViewCell.swift where we designed a UI.
import UIKit class CustomContactsTableViewCell: UITableViewCell { var nameLabel = UILabel() var button = UIButton() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = UITableViewCellSelectionStyle.none let boxView = UIView.init(frame: CGRect(x : 12 , y : 12 , width :UIScreen.main.bounds.size.width - 12*2, height : self.frame.size.height)) self.contentView.backgroundColor = UIColor.clear boxView.backgroundColor = UIColor.white self.contentView.addSubview(boxView) boxView.layer.cornerRadius = 2.0; nameLabel = UILabel(frame:CGRect(x:12 , y:0 , width: boxView.frame.size.width , height: 40) ) boxView.addSubview(nameLabel) nameLabel.textColor = UIColor.black button = UIButton(frame:CGRect(x:boxView.frame.size.width - 90 , y:6 , width: 80 , height: 32) ) boxView.addSubview(button) button.setTitle("Call", for: UIControlState.normal) button.titleLabel?.textColor = UIColor.white button.backgroundColor = UIColor.init(red: 0/255.0, green: 152/255.0, blue: 152/255.0, alpha: 1.0) button.titleLabel?.font = UIFont.systemFont(ofSize: 14.0, weight: 1.0) button.layer.cornerRadius = 2.0 button.addTarget(self, action: #selector(self.callButtonClicked), for: UIControlEvents.touchUpInside) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } 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 callButtonClicked() { print("Call Button Clicked") } }
In this custom cell, we created boxView which contains a name label and one call button. In this way, you create any custom cell as per your need.