[英]Select table cell programmatically in Swift
在 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
上面的//error here
error 处导致此错误: 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
)
我建议不要直接从您自己的代码中调用 UITableView 或 UITableViewDelegate 函数,例如didSelectRow
(或其他 UIKit 标准委托函数),因为它破坏了这些函数的原始设计契约。 如果您直接在 UITableView 对象上调用 didSelectRow,这可能会导致错误或不需要的行为。 相反,在您的类中编写另一个实现 UITableViewDelegate 的自定义函数,您可以在调用 selectRow 后更新适当的 UITableViewCell。 您可以从 didSelectRow 实现中调用相同的函数,从而重用一些代码。
根据您需要对 didSelectRow 方法中的单元格做什么,您可以通过其他方式解决程序化选择场景。 例如:
indexPath == tableView.indexPathForSelectedRow
或检查tableView.indexPathsForSelectedRows?.contains(indexPath) ?? false
tableView.indexPathsForSelectedRows?.contains(indexPath) ?? false
,确定即将显示的单元格是否为选定单元格。 请注意,此时单元格的 isSelected 值可能为 false。 UITableView 将在之后立即需要时将 isSelected 设置为 true。 这导致了第二种选择:override func setSelected(_ selected: Bool, animated: Bool)
。 如果在调用 selectRow 时单元格已经可见,则将立即调用 setSelected。 如果在您调用 selectRow 时单元格不可见,则稍后将在该单元格上调用 setSelected,在调用委托的tableView(_:,cellForRowAt:)
,当用户滚动到该单元格时你很近...
试试这个:
let indexPath = IndexPath(row: 0, section: 0); tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) self.tableView(tableView, didSelectRowAt: indexPath)
编辑
如前所述(这可以在很多地方找到),永远不要调用包含will
、 did
和should
自己的委托方法。
另一种方法可能是:
@objc func simulateSelectRow() -> Void { print("sim") let indexPath = IndexPath(row: 0, section: 0); tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) myDidSelectRowAt(tableView, indexPath: indexPath) } func myDidSelectRowAt(_ tableView: UITableView, indexPath: IndexPath) -> Void { // do what you want when row is selected print("Row:", indexPath.row, "in Section:", indexPath.section, "was selected.") } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { myDidSelectRowAt(tableView, indexPath: indexPath) }
这可能适合也可能不适合您的需求 - 但它可能是一种选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.