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

问题描述 投票:6回答:7

我在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

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

ios uitableview swift3 tableviewcell
7个回答
5
投票

如果你正在使用tableviewcell的xib,那么在viewDidLoad中注册你的xib。

tableView.registerNib(UINib(nibName: "PlaceTableViewCell", bundle: nil), forCellReuseIdentifier: "placeCell")

如果您使用的是uitableViewcell的自定义类,那么试试这个,

let placeCell : PlaceTableViewCell = tableView.dequeueReusableCell(withIdentifier: "placeCell") as! PlaceTableViewCell

正如我所看到的,您的代码工作几乎是正确的。希望我的回答可以帮到你。


17
投票

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

删除它将解决此问题。

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


10
投票

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

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


7
投票

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

only one view on top level

has class and reuse identifier


1
投票

该错误可能会产生误导。我以某种方式将一些视图拖到我的单元格中,它从主视图中创建了另一个视图层次。只是删除你的xib nd错误必须去


0
投票

我有同样的问题,而且我的细胞中没有所有必要的限制。看看这个


0
投票

在我的情况下,它是在单元格外添加的视图。它应该不存在

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.