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

标签 ios cocoa-touch uitableview ios7

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

[tableView 
    setContentOffset:CGPointMake(
        0.0, 
        -tableViewController.topLayoutGuide.length
    ) 
    animated:YES
];

这仅在您第一次调用它之后 有效。在您第一次调用它时,我的表格滚动得比应有的远得多,显示出很多空白。此外,UIRefreshControl出现卡住。你必须稍微推一下 table ,让它弹回真正的顶部。之后,您可以根据需要多次调用此代码,它的行为与您预期的一样。

enter image description here enter image description here

我试过其他方法,但都存在问题。 iOS 6 方式在第一次调用时表现得同样奇怪。虽然它在后续调用中不会跳动太多,但它们是不正确的,因为它滚动到表格顶部下方 64.0 点,因为我们忘记考虑状态和导航栏。

[table setContentOffset:CGPointZero animated:YES];

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

[tableView 
    scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] 
    atScrollPosition:UITableViewScrollPositionTop 
    animated:YES
];

最佳答案

试试这个:

     NSIndexPath* top = [NSIndexPath indexPathForRow:NSNotFound inSection:0];
    [tableView scrollToRowAtIndexPath:top atScrollPosition:UITableViewScrollPositionTop animated:YES];

在 SWIFT 中

    let top = NSIndexPath(forRow: NSNotFound , inSection: 0)
    tableView.scrollToRowAtIndexPath(top, atScrollPosition: .Bottom, animated: true)

Swift 4.0 及以上

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

关于ios - 如何在 iOS 7 中滚动到 UITableView 的顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20206778/

相关文章:

iphone - 当手指经过 TableView 单元格时使其突出显示

iphone - 单击自定义单元格按钮获取节号和行号?

ios - 在 Interface Builder 中设计 UITableView 的部分标题

ios - 我们可以在Apple Watch中设置启动屏幕吗?

ios - UIPicker View 不响应操作表上的完全触摸

ios - 什么是 IOS 中多行文本的最佳文本容器

ios - UITable 滚动不流畅,单元格在 IOS 中显示错误信息

ios - 在 iOS 中访问自定义 UITableViewCell 内的 View

iphone - 使用多种语言的 Storyboard

ios - Swift EXC_BREAKPOINT 在使用 iOS 10.x 但不是 11.x 访问 NSDateComponents 时崩溃