在我的代码中,我有一个包含静态单元格的表格视图(table),它们是在storyboards里创建的。我想在点击最后一个静态单元格时触发一个方法。
我该怎么写代码来实现这个功能?如何在代码中引用静态单元格而不会出错?
在我的代码中,我有一个包含静态单元格的表格视图(table),它们是在storyboards里创建的。我想在点击最后一个静态单元格时触发一个方法。
我该怎么写代码来实现这个功能?如何在代码中引用静态单元格而不会出错?
在viewController中添加:
@property (nonatomic, weak) IBOutlet UITableViewCell *theStaticCell;
将该插座连接到故事板中的单元格。
现在在 tableView:didSelectRowAtIndexPath
方法中:
UITableViewCell *theCellClicked = [self.tableView cellForRowAtIndexPath:indexPath];
if (theCellClicked == theStaticCell) {
//Do stuff
}
使用静态单元格,您仍然可以实现-tableView:didSelectRowAtIndexPath:
并检查indexPath。一种方法是定义特定的indexPath,并使用#define
进行检查,以查看所选行是否在该indexPath上,如果是,则调用[self myMethod]
。
当使用静态和动态单元格混合时,我的建议如下:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let staticIndexPath = tableView.indexPathForCell(self.staticCell) where staticIndexPath == indexPath {
// ADD CODE HERE
}
}
这样可以避免创建新的单元格。我们通常会在cellForRowAtIndexPath
中创建单元格并进行配置。
跟随 CiNN 的回答,这是解决问题的 Swift 3 版本。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let staticIndexPath = tableView.indexPath(for: OUTLET_TO_YOUR_CELL), staticIndexPath == indexPath {
// ADD CODE HERE
}
}
我觉得你遇到了和我一样的问题。每次在重写 tableView:didSelectRowAt
的时候都会出错,原因是我习惯于只调用 super.tableView:didSelectRowAt
,但在这种情况下我们不需要这样做。所以只需移除对父类方法的调用以避免运行时错误。
self.table
更改为self.tableView
。 - Nestor