Thursday, February 7, 2019

Create a Custom UITableViewCell in XIB File

I'm using Xcode 9 and Swift 3 to write this post. I'm going to create a custom UITableViewCell in a separate XIB file and then reuse it by a UITableView in the Main.storyboard file.

NIB files
Cocoa and Cocoa Touch objects are saved as .nib files. A nib file is a description of visual elements of an application's user interfaces such as windows, menus, and controls. The system (MacOS and iOS) uses the description at run-time to create the instances of the UI objects.

XIB files
The .storyboard and .xib files are used in Interface Builder to create the user interface's objects and see the result instantly. A .xib file can contain views or controls or even one controller. The .storyboard file contains the main interface of the application; it might include a .xib file and multiple view controllers. The .xib file is compiled by Xcode as a .nib file, which is loaded by the system at run-time. File's Owner is one of the most important objects of a nib file. The application code accesses the contents of the nib file through it.

1). Creating a Custom UITableViewCell with a XIB File


Go to File > New > File... then under iOS pane, select Cocoa Touch Class and click Next. When a dialog shows up, fill in the details as followings:


After clicking the Next button, two files will be created: HistoryTableViewCell.swift and HistoryTableViewCell.xib.

Click on the HistoryTableViewCell.xib file then add two labels (Operations and Result) then set the constraints properly. After that, click on the File Owner icon (cube icon) then open the Identity Inspector, set Class property to HistoryTableViewCell.


Create two outlets in HistoryTableViewCell.swift which reference Operations and Result labels in HistoryTableViewCell.xib.


2). Reuse the Custom UITableViewCell in Main.storyboard


Drag a UITableView control from the Object Library to Interface Builder and then drag a UITableViewCell control to the UITableView.

Select the Table View Cell then the open the Identity Inspector and set Class setting to HistoryTableViewCell.

3). Register the XIB file in the ViewController


Create an outlet for the UITableView (named historyTableView) in the ViewController.swift and add the following codes to the viewDidLoad() method of the ViewContoller.

historyTableView.register(UINib(nibName: "HistoryTableViewCell", bundle: nil), forCellReuseIdentifier: "historyTableViewCell")
historyTableView.dataSource = self
historyTableView.delegate = self
 

The register(nibName:, forCellReuseIdentifier:) method tells the table view how to create the cell in the nib object (XIB file).

The table view needs a datasource to query data for display. In this case, the ViewController is the datasource because I'll extend it to conforms to UITableViewDataSource.

4). Add Sample Data to the Table View


Add an extension to make ViewController adopt two protocols: UITableViewCellDataSource and UITableViewDelegate.
    
extension ViewController : UITableViewDataSource, UITableViewDelegate {
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = historyTableView.dequeueReusableCell(withIdentifier: "historyTableViewCell") as! HistoryTableViewCell
        cell.operationsLabel.text = "1+2="
        cell.resultLabel.text = "3"
        return cell
    }
}
 

The two methods belong to UITableViewDataSource protocol, and they are required for displaying the data. In this case, the table view has only one row.

The dequeueReusableCell(withIdentifier) method creates an instance of HistoryTableViewCell if not exists in the queue and then reuse it for sub sequent requests.



References
https://developer.apple.com/library/archive/documentation/ToolsLanguages/Conceptual/Xcode_Overview/UsingInterfaceBuilder.html
https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/LoadingResources/CocoaNibs/CocoaNibs.html#//apple_ref/doc/uid/10000051i-CH4


No comments:

Post a Comment