Пользовательский UITableViewCell с кнопкой - PullRequest
0 голосов
/ 19 сентября 2011

Я вложил в UITableViewCell подкласс и добавил к нему кнопку. Как мне отреагировать на событие, когда кнопка нажата? Мне также нужно знать, на какой индексный путь была нажата кнопка.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CustomTableCell";

    CustomTableCell *cell = (CustomTableCell *)
    [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle]
                                    loadNibNamed:@"CustomTableCell"
                                    owner:nil options:nil];
        for (id currentObjects in topLevelObjects){
            if ([currentObjects isKindOfClass:[StatusTableCell class]]){
                cell = (StatusTableCell *) currentObjects;
                break;
            }
        }                           
    }
    cell.customButton.tag = indexPath.row;
    return cell;
}

Ответы [ 2 ]

4 голосов
/ 19 сентября 2011

Если вы добавили UIButton by code в свой подкласс UITableViewCell, вы можете использовать следующий код для добавления действия для него.

//In UITableViewCell subclass
    [customButton addTarget:self 
               action:@selector(aMethod:)
     forControlEvents:UIControlEventTouchDown];

И тогда вы уже написали код для доступа к номеру строки, установив,

 cell.customButton.tag = indexPath.row;

Вы можете получить значение тега в aMethod и получить доступ к значению indexPath.row, как показано ниже,

//In UITableViewCell subclass
    -(IBAction)aMethod:(UIButton*)button
    {
        NSLog(@"indexPath.row value : %d", button.tag);
    }
2 голосов
/ 19 сентября 2011

Вы можете назначить IBAction в перо CustomTableCell и в функции сделать что-то вроде этого:

- (IBAction) btnDoSomethingPressed:(id)sender {
    NSIndexPath *indexPath = [yourTableView indexPathForCell:(UITableViewCell *)[[sender superview] superview]];
     //Use indexPath (or indexPath.row) like you would in a UITableViewDelegate method 
}

Предполагается, что yourTableView - это переменная экземпляра, назначенная вашей таблице.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...