[英]Content views are not displayed on the UITableViewCell
這是我的故事板的一部分:
這是我正在運行的應用程序:
這是我的代碼部分:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
return super.tableView(tableView, cellForRowAt: indexPath)
} else {
tableView.register(SubTextFieldCell.self, forCellReuseIdentifier: "SubTextFieldCell")
let cell = tableView.dequeueReusableCell(withIdentifier: "SubTextFieldCell", for: indexPath) as! SubTextFieldCell
// cell.deleteButton.isEnabled = true
// cell.subTextfield.text = "OK"
print("indexPath.row: \(indexPath.row)")
return cell
}
...
我已經在不同地方連接了按鈕和文本字段,可以保證這部分沒有錯,但是當我單擊第一行中的“添加”按鈕時,我只會得到一個沒有任何內容的單元格。
如果我使用像cell.deleteButton...
這樣的代碼,則Xcode將報告錯誤:
線程1:致命錯誤:展開一個可選值時意外地找到零
然后,我嘗試使用viewWithTag
方法查看是否顯示內容,但仍然收到與以前相同的錯誤。
這是我第一次遇到這種錯誤。 我在其他程序中使用類似的代碼和方法也沒有錯誤。
在情節register(_:forCellReuseIdentifier:)
文件中配置自定義單元格時,不需要調用register(_:forCellReuseIdentifier:)
因為情節register(_:forCellReuseIdentifier:)
應該已經為您完成了。
deleteButton
為nil的原因是因為通過像您一樣重新注冊單元格類,您重寫了故事板為您注冊的內容。 通過使用該重用標識符出隊而創建的所有單元格都不會連接到情節提要,而只是空的。
假設所有@IBOutlet
和重用標識符都已設置(您說過做到了),然后只需使用情節@IBOutlet
中設置的重用標識符使單元出隊。
出隊單元示例:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
return super.tableView(tableView, cellForRowAt: indexPath)
} else {
// Registering again is unnecessary, because the storyboard should have already done that.
// tableView.register(SubTextFieldCell.self, forCellReuseIdentifier: "SubTextFieldCell")
let cell = tableView.dequeueReusableCell(withIdentifier: "SubTextFieldCell") as! SubTextFieldCell
cell.deleteButton.isEnabled = true
cell.subTextfield.text = "OK"
return cell
}
} else {
...
}
}
注意:
即使在確實需要使用表視圖注冊類的情況下,也只需要這樣做一次。 (例如,在viewDidLoad
期間)
即使在那些時候, 也不應該在每次退出單元格時都調用它。 您只是在使您的應用更加努力。
將視圖連接到情節提要中的單元格
確保子視圖( UIButton
等)已通過@IBOutlet
連接到屬性(如下所示的子類代碼)
示例UITableViewController
子類:
class MyTableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyFirstCell", for: indexPath) as! MyFirstTableViewCell
// Configure cell if needed
cell.myButton.setTitle("New Button Text", for: .normal)
cell.myButton.tintColor = .green
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "MySecondCell", for: indexPath) as! MySecondTableViewCell
// Configure cell if needed
cell.myTextField.backgroundColor = .red
return cell
}
}
}
示例UITableViewCell
子類:
class MyFirstTableViewCell: UITableViewCell {
@IBOutlet weak var myButton: UIButton!
}
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.