UIButton inside UITableViewCell steals touch from UITableView

前端 未结 4 714
终归单人心
终归单人心 2021-02-14 21:14

I have a problem similar to this one but answer provided there doesn\'t help much. I have UITableView with some custom UITableViewCells, those cells ha

4条回答
  •  忘了有多久
    2021-02-14 21:37

    Below code works for me:

     - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    cell = [tableView dequeueReusableCellWithIdentifier:@"cell_id"];
    cell.userInteractionEnabled = YES;
    if (cell == nil) {
        cell = [[[CustomCell1 alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell_id"]autorelease];
    }
    
    [cell.button addTarget:self action:@selector(button_action) forControlEvents:UIControlEventTouchUpInside];}
    
    -(void)button_action{NSLog(@"Hello!");}
    

    This is my custom cell:

    #import "CustomCell.h"
    @implementation CustomCell
    @synthesize button;
    
    
    - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        button = [[UIButton alloc]init];
        button =[UIColor redColor];
        [self.contentView addSubview: button];
               }
    return self;}
    
    - (void)layoutSubviews {
    [super layoutSubviews];
    CGRect contentRect = self.contentView.bounds;
    CGFloat boundsX = contentRect.origin.x;
    CGRect frame;
    frame= CGRectMake(boundsX+50 ,+15, 100, 100);
            button = frame;}
    
    - (void)setSelected:(BOOL)selected animated:(BOOL)animated
    {   [super setSelected:selected animated:animated];
    // Configure the view for the selected state
    }
    

提交回复
热议问题