【问题标题】:iPhone:How to get the button action of a customcell from the viewcontroller?iPhone:如何从视图控制器中获取自定义单元格的按钮操作?
【发布时间】:2011-08-22 11:27:54
【问题描述】:

我使用 UITableview,使用 IB 在自定义单元格和一些标签中定义了一个 UIButton,自定义单元格子类已经定义了按钮的 IBAction 和必要的 IBOutlets,但我想在tableview 控制器它自己,但不在自定义单元子类中。

我该怎么做?我还需要获取准确点击了哪一行的按钮,以便显示与其相关的内容。

【问题讨论】:

    标签: iphone ios


    【解决方案1】:

    我通过将它添加到我的控制器中解决了问题;

    [cell.expButton setTag:indexPath.row];
    UIButton *button = (UIButton *)[cell expButton];
    [button addTarget:self action:@selector(buttonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
    

    【讨论】:

      【解决方案2】:

      为了可点击事件(子View上的触摸效果)的需要,我通常是这样做的:

      -(void)viewDidLoad{
          self.tableView.delaysContentTouches = NO;
      
      }
      
      - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
      {
       // This will do the touch down effect on the subView of your UIButton
        for (id obj in cell.subviews)
          {
              if ([NSStringFromClass([obj class]) isEqualToString:@"UITableViewCellScrollView"])
              {
                  UIScrollView *scroll = (UIScrollView *) obj;
                  scroll.delaysContentTouches = NO;
                  break;
              }
          }
      
         // I need to get which row's button is exactly clicked so I will show the content relavant to it.- here it is 
         UIButton *btn = (UIButton*)[cell viewWithTag:200];
         // btn = cell.myButton; If you are connected with the IBOutlet
         [btn setTag:200 + indexPath.row];
         [self.btnPlay addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
      
      }
      
      -(void)btnAction: (id)sender{
          UIButton *btn = (UIButton *)sender;
             NSLog(@"Selected subView of the  Row is  %d th tag", btn.tag-200);
      
         // You can get the UITableViewCell using the tag property
          selectedIP = [NSIndexPath indexPathForRow:btn.tag - 200 inSection:1;
          UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:selectedIP];
      
        // Do the relevant code 
      }
      

      【讨论】:

        【解决方案3】:

        你想要的方式是正确的(MVC 必须如何编码干净) - 太漂亮了!

        为了提高效率,您必须使用委托 - 这是最好的方法! 这是一种如何做到这一点的方法(例如快速)。 https://stackoverflow.com/a/29920564/1415713

        【讨论】:

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