自定义UITableViewCell的accessoryView 判断哪个Button按下

UITableview的开发中经常要自定义Cell右侧的AccessoryView,把他换成带图片的按钮,并在用户Tap时判断出是哪个自定义按钮被按下了。

创建自定义按钮,并设为AccessoryView

if (cell == nil) { 
    cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault                                  reuseIdentifier:identifier]; 
   
    UIImage *image= [ UIImage imageNamed:@"delete.png" ];
    UIButton *button = [ UIButton buttonWithType:UIButtonTypeCustom ];
    CGRect frame = CGRectMake( 0.0 , 0.0 , image.size.width , image.size.height );
    button. frame = frame;
    [button setBackgroundImage:image forState:UIControlStateNormal ];
    button. backgroundColor = [UIColor clearColor ];
    [button addTarget:self action:@selector(buttonPressedAction  forControlEvents:UIControlEventTouchUpInside]; 
    cell. accessoryView = button;
 } 

如果将Button加入到cell.contentView中,也是可以的。

cell.contentView addSubview:button];


在Tap时进行判断,得到用户Tap的Cell的IndexPath

- (void)buttonPressedAction  id)sender 
{ 
   UIButton *button = (UIButton *)sender; 
   (UITableViewCell*)cell = [button superview]; 
   int row = [myTable indexPathForCell:cell].row; 
} 
对于加到contentview里的Button, 
(UITableViewCell*)cell = [[button superview] superview];

你可能感兴趣的:(image,action,button)