[英]Outlets are always nil in custom UITableViewCell
我有一個自定義的 UITableViewCell,我用界面構建器設計了一個標簽和一個選擇器。 對於實現 swift 文件,我添加了兩個出口來引用標簽和選擇器。 插座連接到 ui 元素,代碼如下所示
class TitlePickerCell: UITableViewCell
{
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var picker: UIPickerView!
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
}
}
我有一個 UITableViewController,我想在這個單元格中使用它。 我將它設置為靜態是因為我使用它來顯示設置,並且單元格的數量永遠不會以編程方式改變。 我將我的一個自定義單元格添加到表格視圖並將其標識符設置為 MediaStyleCell。
然后,在 UITableViewController 的 swift 文件中,我將此行添加到我的 viewDidLoad 函數中
self.settingsTable.registerNib(UINib.init(nibName: "TitlePickerCell", bundle: nil), forCellReuseIdentifier: "MediaStyleCell")
其中 TitlePickerCell 是 .xib 文件的名稱,MediaStyleCell 是我使用界面生成器為單元格提供的標識符。 當我運行我的應用程序時,它崩潰了,因為我的自定義單元格類中的標簽和選擇器為零。
如果你使用 tableview.registerClass:forCellReuseIdentifier:但你也有單元格的 xib 文件,你會得到這個錯誤。
所以代替
tablView.register(Cell.self, forCellReuseIdentifier: cellToDisplay.identifier)
只是使用
tableView.register(UINib(nibName: cellToDisplay.identifier, bundle: nil), forCellReuseIdentifier: cellToDisplay.identifier)
我認為發生這種情況的唯一原因是,如果插座未正確鏈接,正在注冊不正確的筆尖/標識符或 .xib 文件中的重用標識符丟失/不正確。
無法重現,這里是我使用的 VC 代碼:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib.init(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "DifferentIdentifier")
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CustomTableViewCell = tableView.dequeueReusableCellWithIdentifier("DifferentIdentifier", forIndexPath: indexPath) as! CustomTableViewCell
cell.titleLabel.text = "HERPITY"
return cell
}
}
這是單元格:
class CustomTableViewCell: UITableViewCell {
@IBOutlet var titleLabel: UILabel!
@IBOutlet var pickerView: UIPickerView!
override func awakeFromNib() {
super.awakeFromNib()
titleLabel.text = "Works"
pickerView.backgroundColor = UIColor.blueColor()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
我得到了這個漂亮丑陋的細胞(我只是把它變成了藍色,因為它是第一次自動完成)
創建自定義 UITableViewCell 似乎是解決此問題的錯誤方法。 只需將單元格樣式設置為自定義並以這種方式添加 UI 元素即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.