简体   繁体   中英

Why is my UITableView not scrolling to the correct index row?

I a UITableView setup and loaded with about 3 records. The height of the UITableView in Interface Builder is only 44 pixels. The height of each row is set to 44 pixels.

This means that only really one row is visible at a time but it is possible to drag and scroll to a new row. I want the UITableView too always show the most visible row scrolled to.

I have setup the following code:

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    // Get the center of the UITableView bounds     
    CGPoint tableViewCenter = self.activeTableView.center;
    // Get the row that is currently occupying the center point in the UITableView  
    NSIndexPath *row = [self.activeTableView indexPathForRowAtPoint:CGPointMake(tableViewCenter.x, tableViewCenter.y)];
    // Animate and scroll to this row making it the only visible row.   
    [self.activeTableView scrollToRowAtIndexPath:row atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

My problem is that no matter what I do, it ALWAYS scrolls back to the 1st row record. I can drag all the way down to the 3rd row and let go, and it scrolls all the way back up to the 1st record? Shouldn't it scroll and center the 3rd row if it's the most visible row after I let go?

Thanks!

Your problem is that tableView.center doesn't change when you scroll. Center only changes if you change the frame of the tableview.

what you should use is the contentOffset of the UIScrollView.

replace your tableViewCenter code with this and it should work

CGPoint tableViewCenter = scrollView.contentOffset;
// contentOffset is the position of the first visible pixel in the upper left corner 
// add half the height so the relevant point is in the middle of the tableView
tableViewCenter.y += self. activeTableView.frame.size.height/2;

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