Task 1. Load UIViewcontroller form Xib
We can load a UIViewcontroller form Xib instead of Storyboard. We can use following procedure:
1. Create a UIViewcontroller.
XCode File -> New -> File -> Cocoa Touch Class -> Fill Class with your class name , subclass of with UIViewController , check Also create Xib file, language Swift -> Next - Create.
Example: ViewControllerFromXib
2. Override init().
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)
{
super.init(nibName: "ViewControllerFromXib", bundle: Bundle.main)
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder:aDecoder)
}
3. Open newly created Controller
let controller = ViewControllerFromXib.init()
self.present(controller, animated: true, completion: nil)
In this above way, We can load a UIViewcontroller from XIB.
Task 2. Create a tableview & populate it's cell using custom xib
1. Create a Custom UItableViewCell
XCode File -> New -> File -> Cocoa Touch Class -> Fill Class with your cell name , subclass of with TableViewCell , check Also create Xib file, language Swift -> Next - Create.
Example: CustomTableViewCell
1.Register UItableViewCell for Your TableView.
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Item"
self.tableView.register(UINib(nibName: "CustomTableViewCell", bundle:Bundle.main), forCellReuseIdentifier: "CustomTableViewCell");
}
2. Implement UITableViewDataSource into Your Viewcontroller
extension ViewControllerFromXib:UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
return cell
}
}
2. Implement UITableViewDelegate into Your Viewcontroller.
extension ViewControllerFromXib:UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
return UITableViewAutomaticDimension;
}
}