在表格视图控制器中调用静态单元格的方法

25

在我的代码中,我有一个包含静态单元格的表格视图(table),它们是在storyboards里创建的。我想在点击最后一个静态单元格时触发一个方法。

我该怎么写代码来实现这个功能?如何在代码中引用静态单元格而不会出错?

5个回答

79

在viewController中添加:

@property (nonatomic, weak) IBOutlet UITableViewCell *theStaticCell;  

将该插座连接到故事板中的单元格。

现在在 tableView:didSelectRowAtIndexPath 方法中:

UITableViewCell *theCellClicked = [self.tableView cellForRowAtIndexPath:indexPath];
if (theCellClicked == theStaticCell) {
    //Do stuff
}

我不得不将 self.table 更改为 self.tableView - Nestor
但它是否经过优化?如果它不是静态单元格,它会创建一个新的单元格吗? - CiNN
也许使用indexPathForCell是最好的选择。 - CiNN
1
@CiNN 仅供记录,这不会创建一个新的单元格。 - Lasse Bunk

9

使用静态单元格,您仍然可以实现-tableView:didSelectRowAtIndexPath:并检查indexPath。一种方法是定义特定的indexPath,并使用#define进行检查,以查看所选行是否在该indexPath上,如果是,则调用[self myMethod]


我尝试过了,当调用indexPath.row时,在运行时会抛出一个错误。我该如何检查第三个section的第二行? - carbonr
if ([indexPath isEqual:[NSIndexPath indexPathForRow:1 inSection:2]]) [self myMethod]; - Sierra Alpha
3
我更喜欢 @MaxGabriel 的回答,因为你可以重新排列单元格而不改变你的代码。 - Frank Schmitt

4

当使用静态和动态单元格混合时,我的建议如下:

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
                    if let staticIndexPath = tableView.indexPathForCell(self.staticCell) where staticIndexPath == indexPath {
// ADD CODE HERE 
                }
        }

这样可以避免创建新的单元格。我们通常会在cellForRowAtIndexPath中创建单元格并进行配置。


1

跟随 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方法,特别是如果您正在故事板上使用静态单元格。

0

我觉得你遇到了和我一样的问题。每次在重写 tableView:didSelectRowAt 的时候都会出错,原因是我习惯于只调用 super.tableView:didSelectRowAt,但在这种情况下我们不需要这样做。所以只需移除对父类方法的调用以避免运行时错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接