Josh Byanec McFergan
Josh Byanec McFergan

Reputation: 491

Position UITableViewCell on Top when Cell is selected

I want that the selected cell will always be at the top most position of tableView. I can to it via:

[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];

but my problem is, when the number of cells, for example, is just 3. When I select cell number 3, it just stays there. Was that the normal behaviour? If yes, then, can you suggest something so that I can achieve my goal? Thanks!

Upvotes: 3

Views: 2023

Answers (3)

Shankar BS
Shankar BS

Reputation: 8402

U can use contentInset and setContentOffset property of tableview for example

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {
    CGFloat height = 44.0f;//cell height
    tableView.contentInset = UIEdgeInsetsMake(0, 0, height * indexPath.row, 0);

   //[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES]; //commenting u are setting it by using setContentOffset so dont use this
    [tableView setContentOffset:CGPointMake(0, (indexPath.row * height) )animated:YES]; //set the selected cell to top
} 

hope this helps u .. :)

Upvotes: 4

Shabeer Ali
Shabeer Ali

Reputation: 1033

you can set UITableView content offset using

[tableView setContentOffset:offsetPoint animated:YES];

or

[tableView setContentOffset:offsetPoint];

and get your selected cell position by

CGPoint offsetPoint = [tableView cellForRowAtIndexPath:indexPath].frame.origin

then you can move cell to your desired offset as bellow

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    float topOffset = 64; //in case of navigationbar
    CGPoint offsetPoint = CGPointMake(0, cell.frame.origin.y - topOffset);
    [tableView setContentOffset:offsetPoint animated:YES];

}

Upvotes: 0

Rohit
Rohit

Reputation: 1174

You can use this code in the didSelectRowAtIndexPath delegate of table view

CGFloat height = 44.0f;//cell height
tableView.contentInset = UIEdgeInsetsMake(0, 0, height * indexPath.row, 0);

[tableView setContentOffset:CGPointMake(0, (indexPath.row * height) )animated:YES];    

Upvotes: 2

Related Questions