简体   繁体   中英

Custom UITableViewCell from a .xib file

I'm trying to use a custom UITableViewCell from a .xib file

In the ViewController where I have the UITableView I already did the following:

Ctrl + Drag the tableViewDataSource and the tableViewDelegate to this View Controller in the Interface Builder.

And this code:

    import UIKit

    class ResultsFoundViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

        @IBOutlet weak var tableView: UITableView!

        override func viewDidLoad() {
            super.viewDidLoad()

            self.tableView.dataSource = self;
            self.tableView.delegate = self;

       //Register my Custom Cell
            let customCellName = String(describing: ResultsFoundTableViewCell.self);
            let customCellNib = UINib.init(nibName: customCellName, bundle: nil);
            self.tableView.register(customCellNib, forCellReuseIdentifier: customCellName);
        }

        public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 5;
        }

        // MARK: UITableViewDataSource Functions

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ResultsFoundTableViewCell", for: indexPath) as! ResultsFoundTableViewCell;
            cell.lbStoreName.text = "Name";

    return cell;
            } 
}

In the CustomCell I only have a label to make it simpler:

import UIKit

class ResultsFoundTableViewCell: UITableViewCell {

    @IBOutlet weak var lbStoreName: UILabel! 
}

The error I get is:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'invalid nib registered for identifier (ResultsFoundTableViewCell) - nib must contain exactly one top level object which must be a UITableViewCell instance'

Do you know why is this happening?

The reason of this problem is that you must put all your UI components inside the cell->contentView , if any element is out of it , the nib registration will fail

Also make nib declaration without Describting

    let customCellNib = UINib.init(nibName: "nibClassName", bundle: nil);
    self.tableView.register(customCellNib, forCellReuseIdentifier: customCellName);

As String(describing here

  let customCellName = String(describing: ResultsFoundTableViewCell.self);

adds optional to string content like this Optional("nibClassName")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM