我想在我的应用程序中重用 UITableViewCell
,但我收到此错误:在隐式展开可选值时意外发现 nil。
我发现这是因为 UITableViewCell
中的 UI 东西是 nil,所以我的应用程序崩溃了。
我的UITableViewCell
代码是这样的:
class WordListCell: UITableViewCell {
@IBOutlet weak var wordListCoverImage: UIImageView!
@IBOutlet weak var wordListName: UILabel!
@IBOutlet weak var wordListInfo: UILabel!
var wordList: WordList? {
didSet {
updateUI()
}
}
private func updateUI() {
wordListName.text = wordList?.name
wordListInfo.text = wordList?.description
wordListCoverImage = UIImage()
}
}
我在 storyboard
中创建它,并将 outlet
链接到另一个 TableView
中的代码。
但是这次,我想在一个新的 TableView
中重用单元格,它都是由代码创建的,所以我不知道如何初始化 UI 的东西。
新的UITableView
代码是这样的:
tableView.delegate = self
tableView.dataSource = self
tableView.register(WordListCell.self, forCellReuseIdentifier: "wordListCell")
//the delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return wordLists.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let wordList = wordLists[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "wordListCell", for: indexPath)
if let wordListCell = cell as? WordListCell {
wordListCell.wordList = wordList
}
return cell
}
请告诉我如何重用电池。谢谢!
最佳答案
好的,所以我认为您做错的是当您创建自定义 tableView 单元格时,您没有分配 UIImage。因此,请尝试这样做 wordListCoverImage = UIImage(named: wordList.imageName)
。
除了添加
tableView.delegate = self
tableView.dataSource = self
tableView.register(WordListCell.self, forCellReuseIdentifier: "wordListCell")
然后在 let cell = tableView.dequeueReusableCell(withIdentifier: "wordListCell", for: indexPath)
将其向下转换为自定义单元格类,如下所示。
let cell = tableView.dequeueReusableCell(withIdentifier: "wordListCell", for: indexPath) as! WordListCell
最后在那个设置下 cell.delegate = self
希望对您有所帮助!
关于ios - 重用 UITableViewCell 时如何初始化 UI 事物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55891802/