gpt4 book ai didi

ios - tableView.cellForRowAtIndexPath 返回 nil,单元格太多(swift)

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:44 25 4
gpt4 key购买 nike

所以我有最奇怪的事情;

我正在循环一个 tableView 以遍历所有单元格。它适用于少于 5 个单元格,但对于更多单元格会因“意外发现 nil”而崩溃。这是代码:

    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
}

如果你想更新单元格的值,你的单元格应该更新数据源项目。例如,您可以为此创建委托(delegate)

protocol UITableViewCellUpdateDelegate {
func cellDidChangeValue(cell: UITableViewCell)
}

将委托(delegate)添加到您的单元格,并假设我们在此单元格中有一个文本字段。我们为 EditingDidChange 事件添加了 didCHangeTextFieldValue: 的目标,因此每次用户在其中输入内容时都会调用它。当他这样做时,我们调用委托(delegate)函数。

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 中添加委托(delegate)

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier", forIndexPath: indexPath)
cell.delegate = self

return cell
}

最后我们实现委托(delegate)方法:

func cellDidChangeValue(cell: UITableViewCell) {

guard let indexPath = self.tableView.indexPathForCell(cell) else {
return
}

/// Update data source - we have cell and its indexPath

}

希望对你有帮助

关于ios - tableView.cellForRowAtIndexPath 返回 nil,单元格太多(swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32748447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com