我正在动态地在每个UITableView单元格上添加UIButton。我想要处理这个UIButton的触摸事件。请您帮忙解决这个问题吗?
谢谢, Vikas
谢谢, Vikas
[myCellButton addTarget:self action:@selector(myCellButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
如果你要全部用代码完成...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Button" forState:UIControlStateNormal];
[button addTarget:self action:@selector(cellButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[button sizeToFit];
[cell.contentView addSubview:button];
}
...
return cell;
}
...
- (IBAction)cellButtonPressed:(id)sender
{
[sender setImage:[UIImage imageNamed:@"newImage"] forState:UIControlStateNormal];
}
但是我建议使用带有委托的UITableViewCell子类。
UIButton
之后添加此目标,然后在初始化单元格时将按钮添加到该单元格。didSelectRowAtIndexPath
方法用于响应点击行本身(单元格/行),而不是按钮。这个目标动作是针对按钮本身的。现在清晰了吗? - Alex Reynolds