【问题标题】:Custom UITableViewCell from a .xib file来自 .xib 文件的自定义 UITableViewCell
【发布时间】:2018-02-17 20:30:22
【问题描述】:

我正在尝试使用 .xib 文件中的自定义 UITableViewCell

在我拥有 UITableView 的 ViewController 中,我已经执行了以下操作:

Ctrl + 将 tableViewDataSource 和 tableViewDelegate 拖到 Interface Builder 中的这个 View Controller。

还有这段代码:

    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;
            } 
}

在 CustomCell 中,我只有一个标签以使其更简单:

import UIKit

class ResultsFoundTableViewCell: UITableViewCell {

    @IBOutlet weak var lbStoreName: UILabel! 
}

我得到的错误是:

由于未捕获的异常而终止应用程序 'NSInternalInconsistencyException',原因:'无效的笔尖注册 对于标识符 (ResultsFoundTableViewCell) - nib 必须完全包含 一个必须是 UITableViewCell 实例的顶级对象'

你知道为什么会这样吗?

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    这个问题的原因是你必须把你所有的UI组件放在cell->contentView里面,如果有任何元素不在里面,nib注册就会失败

    也可以在没有描述的情况下进行 nib 声明

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

    这里是String(describing

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

    像这样 Optional("nibClassName") 为字符串内容添加可选项

    【讨论】:

    • 好的,单元格外的某个地方有一个元素,还没有看到。感谢那!关于 nib 声明:如果我不想像现在这样键入“nibClassName”并从类名中自动获取它怎么办?因此,如果我更改它或我没有正确编写它,它仍然可以工作。
    • 在 nib name 与 class name 不同的情况下会有好处,但在大多数情况下它们是相同的,这很好
    猜你喜欢
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多