简体   繁体   中英

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!

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 .. :)

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];    

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];

}
  • (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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM