【发布时间】:2012-03-31 00:07:47
【问题描述】:
在我的代码中,我在情节提要中有一个带有静态单元格的表格。我试图在单击最后一个静态单元格时触发一个方法。
我应该在代码中写什么来实现这一点。如何在不触发错误的情况下引用代码中的静态单元格。
【问题讨论】:
标签: ios uitableview storyboard
在我的代码中,我在情节提要中有一个带有静态单元格的表格。我试图在单击最后一个静态单元格时触发一个方法。
我应该在代码中写什么来实现这一点。如何在不触发错误的情况下引用代码中的静态单元格。
【问题讨论】:
标签: ios uitableview storyboard
在viewController中添加:
@property (nonatomic, weak) IBOutlet UITableViewCell *theStaticCell;
将该插座连接到情节提要中的单元格。
现在在tableView:didSelectRowAtIndexPath 方法中:
UITableViewCell *theCellClicked = [self.tableView cellForRowAtIndexPath:indexPath];
if (theCellClicked == theStaticCell) {
//Do stuff
}
【讨论】:
self.table 更改为 self.tableView。
使用静态单元格,您仍然可以实现 - tableView:didSelectRowAtIndexPath: 并检查 indexPath。一种方法是使用#define 定义特定的indexPath,并检查所选行是否在该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中创建cell并配置它
【讨论】:
在 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
}
}
这种方法不需要实现 cellForRow 方法,特别是如果您在情节提要上使用静态单元格。
【讨论】:
我想你遇到了和我一样的问题。我在覆盖tableView:didSelectRowAt 时一直出错,原因是我习惯于只调用super.tableView:didSelectRowAt,但在这种情况下我们不想这样做。所以只需移除对超类方法的调用即可避免运行时错误。
【讨论】: