![](/img/trans.png)
[英]tableView.dequeueReusableCellWithIdentifier VS tableView.cellForRowAtIndexPath
[英]tableView.cellForRowAtIndexPath returns nil with too many cells (swift)
所以我有最奇怪的事情;
我正在循環tableView以迭代所有單元格。 它可以在少於5個細胞的情況下正常工作,但是對於更多細胞而言,“意外發現為零”會崩潰。 這是代碼:
for section in 0..<tableView.numberOfSections {
for row in 0..<tableView.numberofRowsInSection(section) {
let indexPath = NSIndexPath(forRow: row, inSection: section)
let cell = tableView?.cellForRowAtIndexPath(indexPath) as? MenuItemTableViewCell
// extract cell properties
最后一行是給出錯誤的那一行。
有什么想法嗎?
因為單元格是重用的,所以只有當給定indexPath的單元格當前可見時,cellForRowAtIndexPath才會為您提供單元格。 它由可選值表示。 如果你想防止崩潰,你應該使用if let
if let cell = tableView?.cellForRowAtIndexPath(indexPath) as? MenuItemTableViewCell {
// Do something with cell
}
如果要更新單元格中的值,則單元格應更新dataSource項目。 例如,您可以為此創建委托
protocol UITableViewCellUpdateDelegate {
func cellDidChangeValue(cell: UITableViewCell)
}
將委托添加到您的單元格,並假設我們在此單元格中有一個textField。 我們為didCHangeTextFieldValue:
添加目標didCHangeTextFieldValue:
對於EditingDidChange事件,每次用戶在其中鍵入somethink時都會調用它。 當他這樣做時,我們稱之為委托功能。
class MyCell: UITableViewCell {
@IBOutlet var textField: UITextField!
var delegate: UITableViewCellUpdateDelegate?
override func awakeFromNib() {
textField.addTarget(self, action: Selector("didCHangeTextFieldValue:"), forControlEvents: UIControlEvents.EditingChanged)
}
@IBAction func didCHangeTextFieldValue(sender: AnyObject?) {
self.delegate?.cellDidChangeValue(cell)
}
}
然后在cellForRowAtIndexPath
添加委托
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier", forIndexPath: indexPath)
cell.delegate = self
return cell
}
最后我們實現了委托方法:
func cellDidChangeValue(cell: UITableViewCell) {
guard let indexPath = self.tableView.indexPathForCell(cell) else {
return
}
/// Update data source - we have cell and its indexPath
}
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.