Search code examples
iosswift3uitableview

I am getting an error - nib must contain exactly one top level object which must be a UITableViewCell instance'"


I am using a custom cell in my tableView but when I run i get the error which I have mentioned in my question.

 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

How can I get rid of this error. I have used different methods for registering a cell in table view. But it does not works. please help


Solution

  • If you are using xib of tableviewcell then register your xib like this in viewDidLoad.

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

    If you are using custom class of tableViewcell then try this one,

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

    As I am seeing your code work is almost correct. Hope my answer helps you.