[英]How to scroll to top in IOS7 UITableView?
在IOS6中,我有以下代碼滾動到UITableView的頂部
[tableView setContentOffset:CGPointZero animated:YES];
在IOS7中,這不再起作用了。 表視圖不會完全滾動到頂部(但幾乎)。
在iOS7中,默認情況下,整個屏幕UITableView和UIScrollView組件調整內容並滾動指示符插入,以使一切正常。 但是,正如您已經注意到CGPointZero不再代表將您帶到視覺“頂部”的內容偏移。
請改用:
self.tableView.contentOffset = CGPointMake(0, 0 - self.tableView.contentInset.top);
在這里,您不必擔心是否有部分或行。 您也不會告訴Table View定位第一行,然后想知道為什么它沒有顯示所有非常高的表頭視圖等。
試試這個:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
基於@Markus Johansson接受的答案,這里是Swift代碼版本:
func scrollToTop() {
if (self.tableView.numberOfSections > 0 ) {
let top = NSIndexPath(row: Foundation.NSNotFound, section: 0)
self.tableView.scrollToRow(at: top as IndexPath, at: .top, animated: true);
}
}
通過這里的一些其他答案的幫助,我設法讓它工作。 為了避免崩潰,我必須首先檢查是否有一些部分。 如果第一部分沒有行,則NsNotFound可用作行索引。 希望這應該是放在UITableViewController中的通用函數:
-(void) scrollToTop
{
if ([self numberOfSectionsInTableView:self.tableView] > 0)
{
NSIndexPath* top = [NSIndexPath indexPathForRow:NSNotFound inSection:0];
[self.tableView scrollToRowAtIndexPath:top atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
}
var indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.sampleTableView.scrollToRowAtIndexPath(indexPath,
atScrollPosition: UITableViewScrollPosition.Top, animated: true)
要么
self.sampleTableView.setContentOffset(CGPoint.zero, animated:false)
float systemVersion= [[[UIDevice currentDevice] systemVersion] floatValue];
if(systemVersion >= 7.0f)
{
self.edgesForExtendedLayout=UIRectEdgeNone;
}
在viewDidLoad()
方法中嘗試此代碼。
這是idStar在更新的Swift 3語法中的答案 :
self.tableView.contentOffset = CGPoint(x: 0, y: 0 - self.tableView.contentInset.top)
隨着動畫:
self.tableView.setContentOffset(CGPoint(x: 0, y: 0 - self.tableView.contentInset.top), animated: true)
斯威夫特3
如果你有表視圖標題CGPointZero可能不適合你,但這總是可以滾動到頂部。
self.tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: UITableViewScrollPosition.top, animated: false)
你仍然可以使用scrollToRowAtIndexPath:
為此目的
我意識到這已經得到了解答,但我只想提出另一種選擇:
CGRect frame = {{0, 0},{1, 1}};
[self.tableView scrollRectToVisible:frame animated:YES];
這始終保證UITableView將滾動到頂部。 接受的答案是:
NSIndexPath* top = [NSIndexPath indexPathForRow:NSNotFound inSection:0];
[self.tableView scrollToRowAtIndexPath:top atScrollPosition:UITableViewScrollPositionTop animated:YES];
我沒有為我工作,因為我滾動到tableHeaderView而不是單元格。
使用scrollRectToVisible
適用於iOS 6和7。
Swift 4 UITableViewExtension:
func scrollToTop(animated: Bool) {
if numberOfSections > 0 {
let topIndexPath = IndexPath(row: NSNotFound, section: 0)
scrollToRow(at: topIndexPath, at: .top, animated: animated)
}
}
在swift我用過:
self.tableView.setContentOffset(CGPointMake(0, 0), animated: true)
但@Alvin George的作品很棒
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.