如何滚动到iOS 7中UITableView的顶部

Pwn*_*ner 4 cocoa-touch uitableview ios ios7

在iOS 7中,我使用以下代码滚动到我的UITableView的顶部.您必须考虑半透明状态栏和导航栏的重叠.

[tableView 
    setContentOffset:CGPointMake(
        0.0, 
        -tableViewController.topLayoutGuide.length
    ) 
    animated:YES
];
Run Code Online (Sandbox Code Playgroud)

此工作仅您第一次调用它时起作用.在你第一次调用它时,我的表滚动得比它应该的更远,显示出很多空白区域.此外,UIRefreshControl似乎已冻结.你必须轻轻推动桌子才能让它恢复到真正的顶部.之后,您可以根据需要多次调用此代码,它的行为与您期望的一样.

在此输入图像描述 在此输入图像描述

我尝试过其他方法,但都有问题.iOS 6的方式在第一次调用时表现得很奇怪.虽然它在后续调用中没有大量跳跃,但它们不正确,因为它滚动到表格顶部以下64.0点,因为我们忘记了状态和导航栏.

[table setContentOffset:CGPointZero animated:YES];
Run Code Online (Sandbox Code Playgroud)

我也尝试滚动到第一个单元格,但它不会在一次调用中滚动到最顶层.每次调用它时,它只会向上滚动一页.

[tableView 
    scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] 
    atScrollPosition:UITableViewScrollPositionTop 
    animated:YES
];
Run Code Online (Sandbox Code Playgroud)

Dha*_*nia 17

试试这个:

     NSIndexPath* top = [NSIndexPath indexPathForRow:NSNotFound inSection:0];
    [tableView scrollToRowAtIndexPath:top atScrollPosition:UITableViewScrollPositionTop animated:YES];
Run Code Online (Sandbox Code Playgroud)

在SWIFT

    let top = NSIndexPath(forRow: NSNotFound , inSection: 0)
    tableView.scrollToRowAtIndexPath(top, atScrollPosition: .Bottom, animated: true)
Run Code Online (Sandbox Code Playgroud)

Swift 4.0及以上版本

 let top = NSIndexPath(row: NSNotFound, section: 0)
 tableView.scrollToRow(at: top as IndexPath, at: .bottom, animated: true)
Run Code Online (Sandbox Code Playgroud)


Vin*_*ain 6

我查看了其他答案,发现以下解决方案对我有用.

-(void) scrollToTop
{
    if ([self numberOfSectionsInTableView:self.tableView] > 0)
    {
        NSIndexPath* top = [NSIndexPath indexPathForRow:NSNotFound inSection:0];
        [self.tableView scrollToRowAtIndexPath:top atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}
Run Code Online (Sandbox Code Playgroud)

希望,它解决了你的问题.


ske*_*tik 0

尝试:

[tableView
    setContentOffset:CGPointMake(
        tableView.contentOffset.x,
        -tableView.contentInset.top
    )
    animated:YES
];
Run Code Online (Sandbox Code Playgroud)