我在确定为什么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
}
}
答案 0 :(得分:0)
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
// }
}