0

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

Image of the solution I need in swift

Smurf123
  • 21
  • 1
  • I'm not sure if asking for code translations is valid on stackoverflow, but in the meantime, but you could try: http://swiftify.com/ – Nerdy Bunz Mar 29 '18 at 02:46

3 Answers3

0

Try:

let nibName = "nameOfYourCellNib"
let cell = Bundle.main.loadNibNamed(nibName, owner: nil, options: nil)?.first as? {YOUR_CELL_CLASS_HERE}
peakingcube
  • 1,388
  • 15
  • 32
0

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

Qi Hao
  • 36
  • 3
0

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 cellForRowAtusing:

let cell: YourCustomTableViewCell = yourTableView.dequeue(indexPath: indexPath)
return cell
RomOne
  • 2,065
  • 17
  • 29
  • 1
    Thanks for the detailed answer and explanation! I managed to solve my issue. Codementor seems like a really useful site to help me with my problems. Thanks again. – Smurf123 Mar 29 '18 at 03:37