rihekopo
rihekopo

Reputation: 3350

Can't select table view cell programmatically

I have a custom UITableViewCell (MyCell) that contains a UIButton and another custom cell. I would like to select the the cell programatically whose UIButton has been tapped by the user. Actually I can call methods at button taps, but can't select the cell. What did I missed? It doesn't crash, it runs, but this code doesn't make any changes except the NSLog.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if ([object[@"num"] isEqualToString:@"one"]) {

        MyCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

         //... cell display
        cell.acceptLabel.tag = indexPath.row;
        [cell.acceptLabel addTarget:self action:@selector(didTapBttn:) forControlEvents:UIControlEventTouchUpInside];
        return cell;

    } else {

        MyCustomTableViewCellB *cellMessage = [tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];

        //... cell display

        return cellMessage;

    }

}

 //1. version
- (void)didTapBttn:(id)sender {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:
     UITableViewScrollPositionNone];
    NSLog(@"button tapped");

}
// 2. version
 - (void)didTapBttn:(id)sender {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

 [self.tableView.delegate tableView:self.tableView didSelectRowAtIndexPath:indexPath];
        NSLog(@"button tapped");

}

Upvotes: 0

Views: 208

Answers (2)

croX
croX

Reputation: 1725

Well, assuming that you made sure that cell.acceptLabel is a UIButton (weird name for a button) and that the if statement is true in your case: Then there is left to say that your first version should be right, except that you use the wrong indexPath. You did assign the cell's indexPath.row as the button's tag (very good). But why don't you use it then?

- (void)didTapBttn:(id)sender {
   NSIndexPath *indexPath = [NSIndexPath indexPathForRow:((UIButton *)sender).tag inSection:0];
  [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
  NSLog(@"button tapped");
}

Try this :)

PS: You should still reconsider the sense behind your approach, though. Selecting a tableview cell is typically done by tapping a cell.

Upvotes: 0

Earl Grey
Earl Grey

Reputation: 7466

Why don't you inside the cell set

-(void)awakeFromNib
{
    //other code...
    self.button.userInteractionEnabled = NO;
} 

The tap will be passed to the cell via responder chain.

Upvotes: 1

Related Questions