我有一個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,大概是爲了跨多個表視圖使用?你可以[考慮這個答案](https://stackoverflow.com/a/37316669/5099014)來確保你已經完成了你需要做的一切。 –