Bogdan Somlea
Bogdan Somlea

Reputation: 624

Select tableViewCell on button click

I have a tableView, with custom cells. In each cell i have a UIButton. When i click the button inside the cell i want that cell to highlight, but when i click o the cell i don't want this to happen. Do you know any way to do this? thank you

until now i have this code:

- (IBAction)buttonMethod: (id)sender {
UIButton *b = (UIButton *) sender;
UITableViewCell *cell = (UITableViewCell *)[[[sender superview] superview] superview];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
[cell setSelected:YES animated:YES];
}

but the cell is highlighted also in -didSelectRow.

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

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
NSAssert(cell, @"cell -> nil");
NSDictionary *cellData = [_data objectAtIndex:indexPath.row];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;

[cell populateCellWithData:cellData];

return cell;
}

Upvotes: 2

Views: 1447

Answers (4)

Michał Ciuba
Michał Ciuba

Reputation: 7944

Use this UITableViewDelegate method:

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    return nil;
}

This way, cells can't be selected when the user taps on them, but you can still select them programatically.

Also using

selectRowAtIndexPath:animated:scrollPosition:

on your UITableView , instead of setSelected:animated: on UITableViewCell might be better. Cells can be reused and the selection will probably disappear when it happens.

Upvotes: 1

soulpark
soulpark

Reputation: 96

Just use UITableViewDelegate like this

-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{

    return NO;
}

but If I were you, I would change the background color of cell in [buttonMethod:] with UITableViewCellSelectionStyleNone

Upvotes: 0

Ritu
Ritu

Reputation: 671

You have to set cell.selectionStyle = UITableViewCellSelectionStyleNone; in cellForRowAtIndexPath method of tableView.

So you can set this style in - (IBAction)buttonMethod: (id)sender. You can add this line at the end. See below:

- (IBAction)buttonMethod: (id)sender {
       UIButton *b = (UIButton *) sender;
       UITableViewCell *cell = (UITableViewCell *)[[[sender superview] superview] superview];
       cell.selectionStyle = UITableViewCellSelectionStyleBlue;
      [cell setSelected:YES animated:YES];
      cell.selectionStyle = UITableViewCellSelectionStyleNone;

}

Upvotes: 0

Ashwinkumar Mangrulkar
Ashwinkumar Mangrulkar

Reputation: 2965

You have to add following line in tableView delegate method cellForRowATIndexPath.

cell.selectionStyle =- UITableViewCellSelectionStyleNone;

Upvotes: 0

Related Questions