【问题标题】:Fire a method from a Static Cell in a Table view Controller从表视图控制器中的静态单元格触发方法
【发布时间】:2012-03-31 00:07:47
【问题描述】:

在我的代码中,我在情节提要中有一个带有静态单元格的表格。我试图在单击最后一个静态单元格时触发一个方法。

我应该在代码中写什么来实现这一点。如何在不触发错误的情况下引用代码中的静态单元格。

【问题讨论】:

    标签: ios uitableview storyboard


    【解决方案1】:

    在viewController中添加:

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

    将该插座连接到情节提要中的单元格。

    现在在tableView:didSelectRowAtIndexPath 方法中:

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

    【讨论】:

    • 我不得不将 self.table 更改为 self.tableView
    • 但是优化了吗?如果它不是静态单元格,它将创建一个新单元格?
    • 也许使用 indexPathForCell 是最好的
    • @CiNN 只是为了后代,这不会创建新单元格。
    【解决方案2】:

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

    【讨论】:

    • 我试过了,当调用 indexPath.row 时,它会在运行时向我抛出一个错误。如何查看第三部分第二行?
    • if ([indexPath isEqual:[NSIndexPath indexPathForRow:1 inSection:2]]) [self myMethod];
    • 我更喜欢@MaxGabriel 的回答,因为您可以在不更改代码的情况下重新排序单元格。
    【解决方案3】:

    这是我在混合静态和动态单元格时的看法,

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

    这避免了创建新单元格。 我们都习惯于在cellForRowAtIndexPath中创建cell并配置它

    【讨论】:

      【解决方案4】:

      在 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 方法,特别是如果您在情节提要上使用静态单元格。

      【讨论】:

        【解决方案5】:

        我想你遇到了和我一样的问题。我在覆盖tableView:didSelectRowAt 时一直出错,原因是我习惯于只调用super.tableView:didSelectRowAt,但在这种情况下我们不想这样做。所以只需移除对超类方法的调用即可避免运行时错误。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多