Basically I need to do what is done here - Not able to add static UITableViewCell into tableview
But I need to do it in swift and I do not know how to convert the objective C solution into swift
Basically I need to do what is done here - Not able to add static UITableViewCell into tableview
But I need to do it in swift and I do not know how to convert the objective C solution into swift
Try:
let nibName = "nameOfYourCellNib"
let cell = Bundle.main.loadNibNamed(nibName, owner: nil, options: nil)?.first as? {YOUR_CELL_CLASS_HERE}
May I know whether you are trying to create static cells or dynamic cells? The solution can be simply changing the cell in the table view instead of adding it in codes or separate xib
First this is not the place to ask for code sample. You should have a look to solutions like Codementor where you can find exactly the kind of help you need ;)
They are different approaches to your problem.
First, you are using a xib, which makes it impossible to add cells in it. Instead you couldd use a storyboard. In that case you'll be able to do whatever you want and add custom cell.
1 - If you really have to use xib, then you can load custom cells by using alanlo approach. I would suggest to use an extension to register your custom cell like so:
extension UITableViewCell {
class func register(tableView: UITableView) {
let identifier = String(describing: self)
let nib = UINib(nibName: identifier, bundle: nil)
tableView.register(nib, forCellReuseIdentifier: identifier)
}
}
Note that your cell identifier will need to have the same name as your custom tableviewcell class (here it would be YourCustomCellTableViewCell)
2- Then in viewdidload
:
YourCustomCellTableViewCell.register(tableView: yourTableView)
3 - Then thanks to the fallowing extension you can easily dequeue your cell:
extension UITableView {
func dequeue<T: UITableViewCell>(indexPath: IndexPath) -> T {
let identifier = String(describing: T.self)
guard let cell = dequeueReusableCell(withIdentifier: identifier, for: indexPath) as? T else {
fatalError()
}
return cell
}
}
4 - dequeue it in the cellForRowAt
using:
let cell: YourCustomTableViewCell = yourTableView.dequeue(indexPath: indexPath)
return cell