【问题标题】:IPhone Application Scroll to given position in UITableView when page loaded当页面加载时,iPhone 应用程序滚动到 UITableView 中的给定位置
【发布时间】:2011-08-12 09:29:20
【问题描述】:
我想向下滚动到表格视图中的给定行。
如果我在按钮事件中使用以下代码,它可以正常工作。
[planTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:7 inSection:0 ] atScrollPosition:0 animated:YES];
但我想在页面加载后立即执行此操作。将上述代码放在 viewDidLoad 或 viewDidAppear 中不起作用。
有什么帮助吗??
【问题讨论】:
标签:
iphone
xcode
xcode4.2
【解决方案1】:
这有点 hack,但您也可能希望执行 -scrollToRowAtIndexPath:atScrollPosition:animated: 有一些延迟,因为当调用 -viewDidLoad 或 -viewDidAppear: 时,尚未创建表视图行,所以什么都没有滚动到。
所以:
- (void)doScrolling
{
[planTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:7 inSection:0 ] atScrollPosition:0 animated:YES];
}
并在 -viewDidAppear 中:
[self performSelector:@selector(doScrolling) withObject:nil afterDelay:0.3];
还要注意 atScrollPosition: 参数。实际上是枚举:
typedef enum {
UITableViewScrollPositionNone,
UITableViewScrollPositionTop,
UITableViewScrollPositionMiddle,
UITableViewScrollPositionBottom
} UITableViewScrollPosition;
所以如果该行可见并且传递了0,则不会执行滚动
【解决方案2】:
UITableView 是UIScrollView 的子类,因此您只需在viewDidLoad: 或viewWillAppear 中设置tableView 的contentOffset。
如果您需要向下滚动 7 个表格视图单元格的长度,请计算这 7 个单元格的高度(默认为 44 像素,但如果您有自定义单元格高度,则需要将其考虑在内)并将 contentOffset 设置为CGPointMake(0, *calculated height*)。如果是 7 个 44px 高度的单元格,则为CGPointMake(0, 308)。