Zhen
Zhen

Reputation: 12431

Objective C: How to highlight the first cell in table view when view loads?

I am trying to default the top cell in my table view to be highlighted whenever the subview appears.

I tried to do this:

switch(indexPath.row) { // assuming there is only one section
    case 0:
      cell.textLabel.text = @"First Cell:";
      cell.highlighted = YES
      break;

But this doesn't work as I get a black overlay on my first cell instead.

EDIT (added screenshot)

enter image description here

Any advise on this will be greatly appreciated!

Thanks

Zhen

Upvotes: 1

Views: 2008

Answers (2)

Robert Wagstaff
Robert Wagstaff

Reputation: 2674

I had the exact same problem. You need to move your code into willDisplayCell, instead of cellForRowAtIndexPath.

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    if(indexPath.row == 0) {

        [cell setSelected:YES animated:NO];
    }
}

Upvotes: 4

EmptyStack
EmptyStack

Reputation: 51374

I think what you need is,

cell.selected = YES;

If you want it animated you can use,

[cell setSelected:YES animated:YES];

Upvotes: 3

Related Questions