在iOS 7中,我使用以下代码滚动到UITableView的顶部。您必须考虑半透明状态栏和导航栏的重叠。
[tableView
setContentOffset:CGPointMake(
0.0,
-tableViewController.topLayoutGuide.length
)
animated:YES
];
此作品仅在您第一次调用之后工作。在你第一次调用它时,我的表滚动得比它应该的更远,显示出很多空白区域。此外,UIRefreshControl似乎已冻结。你必须轻轻推动桌子才能让它恢复到真正的顶部。之后,您可以根据需要多次调用此代码,它的行为与您期望的一样。
我尝试过其他方法,但都有问题。 iOS 6的方式在第一次调用时表现得很奇怪。虽然它在后续调用中没有大量跳跃,但它们不正确,因为它滚动到表格顶部以下64.0点,因为我们忘记了状态和导航栏。
[table setContentOffset:CGPointZero animated:YES];
我也尝试滚动到第一个单元格,但它不会在一次调用中滚动到最顶层。每次调用它时,它只会向上滚动一页。
[tableView
scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
atScrollPosition:UITableViewScrollPositionTop
animated:YES
];
答案 0 :(得分:17)
试试这个:
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)
答案 1 :(得分:6)
我查看了其他答案,发现以下解决方案对我有用。
-(void) scrollToTop
{
if ([self numberOfSectionsInTableView:self.tableView] > 0)
{
NSIndexPath* top = [NSIndexPath indexPathForRow:NSNotFound inSection:0];
[self.tableView scrollToRowAtIndexPath:top atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
}
希望,它解决了你的问题。
答案 2 :(得分:2)
它不是"魔术"。 64偏移用于状态栏(20点)和导航栏(44点)高度。如果滚动视图的偏移量为0并且您还有状态栏+导航栏,则它将位于这些对象下,您将看到原始内容的-64.0。在故事板中有一个选项"调整滚动视图插图"这是默认情况下检查的
答案 3 :(得分:0)
尝试:
[tableView
setContentOffset:CGPointMake(
tableView.contentOffset.x,
-tableView.contentInset.top
)
animated:YES
];
答案 4 :(得分:0)
请试试这个:
- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated;
样本是这样的:
[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:0 animated:YES];
答案 5 :(得分:0)
在Objective-C
中[mainTableView setContentOffset:CGPointZero animated:YES];
在斯威夫特:
mainTableView.setContentOffset(CGPointZero, animated:true)
答案 6 :(得分:0)
目标C
NSIndexPath* top = [NSIndexPath indexPathForRow:NSNotFound inSection:0];
[self.tableView scrollToRowAtIndexPath:top atScrollPosition:UITableViewScrollPositionTop animated:YES];
在Swift中
var scrollIndexPath: NSIndexPath = NSIndexPath(forRow:NSNotFound , inSection: 0)
self.tableview.scrollToRowAtIndexPath(scrollIndexPath, atScrollPosition: UITableViewScrollPosition.top, animated: true)
答案 7 :(得分:-1)
iOS scrollview表现得有些奇怪。如您所述,64.0偏移量被“神奇地”添加到视图层次结构中的第一个滚动视图“第一次”。我还没弄清楚为什么会这样。目前我只有一个真正的hackish解决方案:你可以添加一个虚拟滚动作为视图层次结构中的第一个滚动,高度设置为0.之后,你的解决方案应该照常工作。![在此输入图像描述] [ 1]
希望这有帮助。
其他人都知道为什么会发生这种情况?