首页 > 解决方案 > TableViewCell 仅返回 Nil

问题描述

我无法确定为什么 tableViewCell 一直返回 nil。这是我几乎可以肯定导致问题的代码块。

func tableView(tableView: UITableView, cellForRowAt indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "CollectionCell", for: indexPath as IndexPath) as? CollectionViewCell

    if cell == nil {
        var nib = Bundle.main.loadNibNamed("CollectionCell", owner: self, options: nil)
        cell = nib![0] as? CollectionViewCell
    }

    if cell == nil {
        cell = tableView.dequeueReusableCell(withIdentifier: "CollectionCell") as! CollectionViewCell
    }

    // ...

}

这是所要求的整个 CollectionViewCell 文件。

class CollectionViewCell: UITableViewCell {
@IBOutlet weak var txtNameCollection: UITextField!

@IBOutlet weak var btnGoToCollection: UIButton!

@IBOutlet weak var imgShelf: UIImageView!

@IBOutlet weak var btnNameCollection: UIButton!

@IBOutlet weak var btnEditCollectionName: UIButton!

@IBOutlet weak var imgNameCollection: UIImageView!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

标签: iosswift

解决方案


   override func viewDidLoad() {
          super.viewDidLoad()
          tableView.register(UINib(nibName: "CollectionCell", bundle: nil), forCellReuseIdentifier: "CollectionCell")
   }

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

       //var cell = tableView.dequeueReusableCell(withIdentifier: "CollectionCell", for: indexPath as IndexPath) as? CollectionViewCell
       var cell = tableView.dequeueReusableCell(withIdentifier: "CollectionCell" ) as? CollectionViewCell

       cell?.txtNameCollection.text = "Text"
       return cell

       You have to delete this because you use Xib File. And you dont do prototype cell on storyboard. There is no need. Just create a tableView with name is tableView
   //    if cell == nil {
   //        cell = tableView.dequeueReusableCell(withIdentifier: "CollectionCell") as! CollectionViewCell
   //    }

   //    if cell == nil {
   //        var nib = Bundle.main.loadNibNamed("CollectionCell", owner: self, options: nil)
   //        cell = nib![0] as? CollectionViewCell
   //    }

   }

推荐阅读