Reputation:
I have created a custom UITableViewCell
named CustomTableViewCell
having xib.
The code for the CustomTableViewCell
is as follows-
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var label1: UILabel!
}
In a UITableViewController
, I use the CustomTableViewCell
as follows-
in viewDidLoad()
, the register(_:forCellReuseIdentifier:)
is called.
in tableView(_:cellForRowAt:)
function, the dequeueReusableCell(withIdentifier:for:)
is called and the text for the label1
is set.
The code works as expected and the CustomTableviewCell
is visible when the app is run.
There is another custom UIViewController
with xib. To this xib file, I would like to add the CustomTableViewCell
as a subView.
I added a UIView
to the xib and set it's class to CustomTableViewCell
. When the app is run, the app crashes because the label
IBOutlet is nil.
Can anyone point out how to fix this issue?
Upvotes: 0
Views: 185
Reputation: 1
To add a custom UIViewcell , you can create uiviewcell using xib and give the particular cell a reusable identifier..then use that particular uiview cell while defining tableviewcell in the uiviewcontroller.
Upvotes: 1
Reputation: 28
The thing you are trying to do is achieveable but in a different way. UITableView cells are automatically instantiated by UITableViews only. So by setting the class name won't instantiate the CustomTableViewCell.
The solution is: Every UITableView cells are subclass of UIView, so what we can do is instantiate the CustomTableView cell ourself through nib and add the view programmatically in a container view which we can put in the UIViewController.
Here is the code that might help you.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var containerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: String(describing: CustomTableViewCell.self), bundle: nil)
if let customTableViewCell = nib.instantiate(withOwner: self, options: nil).first as? CustomTableViewCell {
customTableViewCell.label1.text = "Hello"
containerView.addSubview(customTableViewCell)
}
}
}
Upvotes: 0