1

I need to programmatically select a UITableViewCell, I have tried this:

NSIndexPath *selectedCellIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [table selectRowAtIndexPath:selectedCellIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];

However, it only selects the cell visually and doesn't pick up on that selection in didSelectRowAtIndexPath unless you actually tap the cell.

Any ideas, has anyone experienced this or have ideas to get around this or approach it differently?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Josh Kahane
  • 16,765
  • 45
  • 140
  • 253
  • 1
    possible duplicate of [Select tableview row programmatically](http://stackoverflow.com/questions/2035061/select-tableview-row-programmatically) – jscs Feb 23 '12 at 20:55

3 Answers3

9

Why not send a message to didSelectRowAtIndexPath after you've sent a message to selectRowAtIndexPath? The code should look like this:

NSIndexPath *selectedCellIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[table selectRowAtIndexPath:selectedCellIndexPath 
                   animated:YES 
             scrollPosition:UITableViewScrollPositionNone];
[table.delegate tableView:table didSelectRowAtIndexPath:selectedCellIndexPath];
Wayne Hartman
  • 18,369
  • 7
  • 84
  • 116
Aaron Hayman
  • 8,492
  • 2
  • 36
  • 63
  • 1
    You already know the index path you want to select, so try this: [table.delegate tableView:table didSelectRowAtIndexPath:selectedCellIndexPath]; – Aaron Hayman Feb 23 '12 at 20:56
3

By wanting it pressed, I'm guessing you just want to run the code in didSelectRow?

Whatever you have in your didSelectRow method, can't you put it in a seperate method of its own and just call it?

Darren
  • 10,182
  • 20
  • 95
  • 162
0

If you subclass your UITableView it's possible to customize UIEvent that occurs on each TableViewCells. Your controller will respond to Touch Events:

  • touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  • touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
  • touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
  • touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event

For each event you have a NSSET of touches and you can find your UitableViewCell Exemple :

 - touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    for(UITouch *aTouch in touches){
        if(aTouch.view IsYourUiTableViewCell){
           NSLOG(@"TableViewCell press!");
        }
    }
  }
user1226119
  • 324
  • 3
  • 6