iPhone:如何从viewcontroller获得一个自定义单元的按钮动作?

问题描述:

我使用UITableview,使用IB我在自定义单元格和一些标签中定义了一个UIButton,自定义单元格子类已经有IBAction的按钮和必要的IBOutlets的定义,但我想处理tableview中的按钮单击事件控制器它自己但不在自定义单元格子类中。iPhone:如何从viewcontroller获得一个自定义单元的按钮动作?

我该怎么做?我也需要得到哪一行的按钮是完全点击的,所以我会显示与它相关的内容。

我解决了问题,加入到我的控制器;

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

谢谢!它帮助:) – nithinreddy

+0

@nithinreddy我很高兴! – Spring

对于需要点击事件(触摸子视图效应),我通常这样做:

-(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 
} 

要如何做的方式,这是正确的(MVC怎么也得编码干净) - 多数民众赞成在美丽!

为了让它更有效率,你必须使用委托 - 这是如何做到这一点的最佳方式! 在这里你可以做到这一点(例如迅速)。 https://*.com/a/29920564/1415713