Swift 3 - UITableViewCell未捕获的异常导致崩溃
问题描述:
我有一个UIViewController
与UISearchBar
和UITableView
。当我在搜索栏中输入内容时,它应该在TableViewCell中显示该字符串。直到我开始为TableViewCell使用.xib时,它一切正常。现在,当我在搜索栏中输入文本时,应用程序崩溃并按搜索。控制台上写着:Swift 3 - UITableViewCell未捕获的异常导致崩溃
终止应用程序由于未捕获的异常 'NSUnknownKeyException', 原因: '[UITableViewCell的0x7f8456800c00的setValue:forUndefinedKey:]: 这个类不是密钥值符合编码-的关键 artistNameLabel。'
这里是的.xib:
import UIKit
class SearchResultCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var artistNameLabel: UILabel!
@IBOutlet weak var artworkImageView: 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
}
}
下面是相关的ViewController代码:
extension SearchViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if !hasSearched {
return 0
} else if searchResults.count == 0 {
return 1
} else {
return searchResults.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if searchResults.count == 0 {
return tableView.dequeueReusableCell(withIdentifier: TableViewCellIdentifiers.nothingFoundCell, for: indexPath)
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCellIdentifiers.searchResultCell, for: indexPath) as! SearchResultCell
let searchResult = searchResults[indexPath.row]
cell.nameLabel.text = searchResult.name
cell.artistNameLabel.text = searchResult.artistName
return cell
}
}
}
答
这是最经常通过在故事板或XIB “断开连接” 插座连接引起的。你的情况,我认为这是因为你需要设置表视图单元格的类为SearchResultCell
。我这样说是因为您的错误信息应该输出
“[SearchResultCell 0x7f8456800c00的setValue:forUndefinedKey:]:
我提供了一个初步的答案,但你的情况,实际上可能是,如果你实际上要复杂得多将你的单元分成它自己的xib,大概是为了跨多个表视图使用?你可以[考虑这个答案](https://stackoverflow.com/a/37316669/5099014)来确保你已经完成了你需要做的一切。 –