在Swift中,我可以选择一个表格单元格,如下所示:
let indexPath = IndexPath(row: 0, section: 0);
tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
但是尝试这样调用didSelectRowAt
:
tableView.delegate?.tableView!(tableView, didSelectRowAt: indexPath)
哪个触发:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = categoryListView.cellForRow(at: indexPath) as! CategoryCellView // error here
//do other stuff
}
并在//error here
上面导致此错误:Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
我将此类用于CategoryCellView
单独的笔尖:
@IBDesignable
class CategoryCellView: UITableViewCell {
@IBOutlet weak var myCategoryView: Category!
var categoryId: Int?
var index: Int?
}
我如何didSelectRowAt
在这里触发?
cellForRow(at: indexPath)
如果该单元格不可见,则可以返回nil-并且在调用selectRow之后该单元格可能不可见。因此,我建议更新您的didSelectRow实现,以避免as!
强行展开并且更具防御性:
if let cell = categoryListView.cellForRow(at: indexPath) as? CategoryCellView {
// do stuff with the cell
}
(或者,guard let
如果更有意义,则可以使用)
我建议不要直接didSelectRow
从您自己的代码中调用UITableView或UITableViewDelegate函数(例如(或其他UIKit标准委托函数)),因为这会破坏这些函数的原始设计约定。如果直接在UITableView对象上调用didSelectRow,则可能导致错误或不良行为。相反,在您的类中编写另一个实现UITableViewDelegate的自定义函数,您可以在其中调用selectRow后更新相应的UITableViewCell。您可以从didSelectRow实现中调用相同的函数,从而重用一些代码。
根据您对didSelectRow方法中的单元格需要执行的操作,可以通过其他方式解决编程选择方案。例如:
indexPath == tableView.indexPathForSelectedRow
或检查tableView.indexPathsForSelectedRows?.contains(indexPath) ?? false
,以确定将要显示的单元格是否为选定的单元格。请注意,此时,单元格的isSelected值可能为false。之后,如果需要,UITableView会将isSelected设置为true。这导致第二种选择:override func setSelected(_ selected: Bool, animated: Bool)
如果您只需要更新特定表格视图单元格的外观,则在CategoryCellView中实现。如果在调用selectRow时该单元格已经可见,则setSelected将立即被调用。如果在调用selectRow时该单元格不可见,则tableView(_:,cellForRowAt:)
在用户滚动到该委托的调用之后,稍后将立即在该单元格上调用setSelected本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句