我收到一个错误 - nib必须包含一个顶级对象,该对象必须是UITableViewCell实例'"

Rak*_*han 6 uitableview tableviewcell ios swift3

我在tableView中使用自定义单元格,但是当我运行时,我得到了我在问题中提到的错误.

 self.districtTableView.register(UINib(nibName: "PlaceCollectionViewCell", bundle: nil), forCellReuseIdentifier: "placeCell")

 func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    return false
}

func textFieldDidEndEditing(_ textField: UITextField) {
    // TODO: Your app can do something when textField finishes editing

    print("The textField ended editing. Do something based on app requirements.")
}

func numberOfSections(in tableView: UITableView) -> Int {
     return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return districts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "placeCell") as! PlaceTableViewCell
    // Set text from the data model
    cell.distLabel.text = districts[indexPath.row]
    cell.textLabel?.font = distTextField.font
    return cell
Run Code Online (Sandbox Code Playgroud)

我怎样才能摆脱这个错误.我在表视图中使用了不同的方法来注册单元格.但它不起作用.请帮忙

Pra*_*iya 28

我在Interface builder(XIB)中添加了Tap手势.

删除它将解决此问题.

您必须以编程方式在xib中添加手势

  • 但为什么会这样?? (13认同)

小智 11

在.xib文件中具有多个表视图单元格也会导致此错误.将表视图单元格移动到它们各自的.xib文件中解决了我的错误.

nib必须只包含一个顶级对象,该对象必须是UITableViewCell实例


mrv*_*rvn 8

打开"PlaceCollectionViewCell.xib"文件.确保只有一个顶级视图(查看侧面板,而不仅仅是画布,它可能不可见).确保您的视图具有指定的类,该类是UITableViewCell的子类(不是UICollectionViewCell,xib名称看起来对我很可疑),以及重用标识符.

顶级只有一个视图

有类和重用标识符

  • 我以某种方式将一些视图拖到我的单元格中并导致崩溃。非常感谢,节省了我一些时间。 (4认同)

mil*_*czi 7

就我而言,是在单元外部添加的视图。它不应该去那里

在此处输入图片说明


Shu*_*oel 6

该错误可能具有误导性。我以某种方式将一些视图拖到我的单元格中,它从主视图中创建了另一个级别的视图。只需从您的 xib 中删除它 nd error must go

  • 我也发生过。我以某种方式在 Xib 文件的单元格之外创建的额外标签可能会导致此令人困惑的错误消息。 (2认同)

dah*_*boy 5

如果您正在使用tableviewcell的xib,请在viewDidLoad中像这样注册您的xib。

tableView.registerNib(UINib(nibName: "PlaceTableViewCell", bundle: nil), forCellReuseIdentifier: "placeCell")
Run Code Online (Sandbox Code Playgroud)

如果您使用的是tableViewcell的自定义类,请尝试使用这一类,

let placeCell : PlaceTableViewCell = tableView.dequeueReusableCell(withIdentifier: "placeCell") as! PlaceTableViewCell
Run Code Online (Sandbox Code Playgroud)

正如我所见,您的代码工作几乎是正确的。希望我的回答对您有所帮助。