Как установить действие для UIButton в UITableViewCell

У меня XIB файл TimerCell.xib с UITableViewCell. В другом классе в cellForRowAtIndexPath я инициализирую этот 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];

В моем TimerCell у меня есть два UILabel и один UIButton. Для этой кнопки я хотел бы установить действие для некоторого метода.

Как я могу это сделать? И как показать в первых UILabel данные с моего таймера обратного отсчета фона в реальном времени?

Ответы

Ответ 1

Этот фрагмент кода поможет вам

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);
}

Надеюсь, это поможет!!!

Ответ 2

Поскольку у вас есть подкласс UITableViewCell с именем TimerCell, вы можете добавить свойства outlet в TimerCell. Например:

@interface TimerCell : UITableViewCell

@property (nonatomic, strong) UIButton *button;
@property (nonatomic, strong) UILabel *label;

@end

В TimerCell.xib подключите розетки к кнопке и метке.

Затем в tableView:cellForRowAtIndexPath: вы можете легко получить доступ к кнопке, чтобы установить ее цель и действие:

static NSString *CellIdentifier = @"cellTimer";
TimerCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TimerCell"owner:self options:nil];
    cell = [nib objectAtIndex:0];
}

[cell.button addTarget:self action:@selector(cellButtonWasTapped:)
    forControlEvents:UIControlEventTouchUpInside];;

Вы можете получить доступ к метке ячейки, используя ее свойство label, чтобы обновить ее при срабатывании таймера.

Другой способ доступа к кнопке и метке - использовать теги просмотра, как я описал в этом ответе.

В cellButtonWasTapped: (или любое другое действие, которое вы отправляете с помощью кнопки), вы, вероятно, захотите найти путь индекса ячейки, содержащей кнопку. Я объясню, как это сделать в этом ответе.

Ответ 3

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"cellTimer";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
NSInteger index = indexPath.row;
UILabel *titleLabel = (UILabel *)[cell viewWithTag:101];
UIButton *button = (UIButton *)[cell viewWithTag:100];
[button addTarget:self action:@selector(MethodName:) forControlEvents:UIControlEventTouchUpInside];
}

И установите теги UIButton и UILabel в свой XIB файл TimerCell.xib

Ответ 4

Пожалуйста, сделайте лучшее исследование перед публикацией на SO. Вот код для добавления кнопки в ячейку

UIButton *Button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[Button addTarget:self action:@selector(MethodName:) forControlEvents:UIControlEventTouchUpInside];
[Button setTitle:@"ButtonTitle" forState:UIControlStateNormal];
Button.frame = CGRectMake(100.0, 10.0, 40.0, 40.0);
[cell.contentView addSubview:Button];