How to set Action for UIButton in UITableViewCell

ios, uitableview

Solution

This piece of code will help you

static NSString *CellIdentifier = @"cellTimer";
TimerCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    //cell = [[TimerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TimerCell"owner:self options:nil];
    cell = [nib objectAtIndex:0];
    UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.tag=indexPath.row;
   [button addTarget:self 
       action:@selector(aMethod:) forControlEvents:UIControlEventTouchDown];
   [button setTitle:@"cellButton" forState:UIControlStateNormal];
    button.frame = CGRectMake(80.0, 0.0, 160.0, 40.0);
    [cell.contentView addSubview:button];
   }

  return cell;
}


-(void)aMethod:(UIButton*)sender
{
 NSLog(@"I Clicked a button %d",sender.tag);
}

Hope this helps!!!

Problem

I have `XIB` file TimerCell.xib with `UITableViewCell`. In other class in cellForRowAtIndexPath I initialize this `UITableViewCell`: ``` static NSString *CellIdentifier = @"cellTimer"; TimerCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { //cell = [[TimerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TimerCell"owner:self options:nil]; cell = [nib objectAtIndex:0]; ``` In my TimerCell I have two `UILabel` and one `UIButton`. For this button I would like to set action to some method. How can I do that? And how to show in the first `UILabel` the data from my background countdown timer in real time?

Original source

Related problems