【问题标题】:get section number and row number on custom cells button click?在自定义单元格按钮单击上获取节号和行号?
【发布时间】:2009-05-30 15:41:22
【问题描述】:

我有自定义单元格的表格视图。表格分为许多部分和行。我在单元格上有一个自定义按钮。现在我想在单击该按钮时获取节号和行号。? 关于这个的任何想法

【问题讨论】:

    标签: iphone objective-c cocoa-touch


    【解决方案1】:

    您需要在视图控制器上实现 UIControl 事件处理方法,并将其设置为 所有 按钮的处理程序。即在您的 -tableView:cellForRowAtIndexPath: 函数中,您可以执行以下操作:

    [theCell.button addTarget: self
                       action: @selector(buttonPressed:withEvent:)
             forControlEvents: UIControlEventTouchUpInside];
    

    那么您的事件处理程序将如下所示:

    - (void) buttonPressed: (id) sender withEvent: (UIEvent *) event
    {
        UITouch * touch = [[event touches] anyObject];
        CGPoint location = [touch locationInView: self.tableView];
        NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: location];
    
        /* indexPath contains the index of the row containing the button */
        /* do whatever it is you need to do with the row data now */
    }
    

    【讨论】:

    • 轻微修正... [event touches] 应该是 [event allTouches]
    【解决方案2】:

    一些想法:

    您可以遍历按钮的超级视图层次结构,直到找到 UITableViewCell,然后在 UITableView 上调用 - (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell。

    - (void)buttonClicked:(id)sender {
      UIView *button = sender;
    
      for (UIView *parent = [button superview]; parent != nil; parent = [parent superview]) {
        if ([parent isKindOfClass: [UITableViewCell class]]) {
          UITableViewCell *cell = (UITableViewCell *) parent;           
          NSIndexPath *path = [self.tableView indexPathForCell: cell];
    
          // now use the index path
    
          break; // for
        }
      }
    }
    

    您可以交替使用按钮的标记来存储引用该行的索引。这仅包含一个整数,因此当您只有一个部分或将行作为平面列表管理时最有意义。

    您可以交替使用 UITableViewCell 子类来封装按钮。您的 UITableViewCell 可以响应按钮事件并将事件重新广播给它自己的委托,传递 self.然后事件委托可以在 UITableView 上调用 - (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell 来获取索引路径。

    【讨论】:

      【解决方案3】:

      当您在 tableView 中选择一个单元格时,会调用以下方法:

      - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
      

      访问节号:int section = indexPath.section;

      访问行号(在正确的部分内):int row = indexPath.row;

      【讨论】:

      • 当用户点击一行按钮时不会调用它;只有当他们点击行背景本身时才会调用它。
      【解决方案4】:

      UITableViewcan convert a CGPoint coordinate into an indexPath

      -(NSIndexPath *)indexPathForRowAtPoint:(CGPoint)point
      

      【讨论】:

        【解决方案5】:

        添加你的 UITableViewCell 子类的实例变量来存储单元格的索引路径:

        NSIndexPath *myIndexPath;
        

        当您在以下位置创建单元格时:

        cellForIndexPath:
        

        将索引路径传递给新创建/回收的单元格。

        现在,当您按下按钮时,只需从单元格的 ivar 中读取 indexpath。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-17
          • 2019-01-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多