【发布时间】:2015-04-02 00:27:29
【问题描述】:
我有一个 100 行的表格,想以编程方式将其滚动到任何元素并选择该元素。在第一个控制器中,我指定行和部分,并将带有 UITableView 的控制器推送到导航堆栈上。在“tableView-controller”的viewWillAppear 中,我使用代码:
[tableView_ selectRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section] animated:NO scrollPosition:UITableViewScrollPositionMiddle];
奇怪的是,它完美地滚动到 99 个第一行中的任何一个,第 100 行被选中,但仍然“低于”可见区域。我必须手动滚动表格才能显示它。
如果我将该代码放在viewDidAppear 中,表格可以很好地滚动,但会出现明显的延迟。
我还尝试了什么:
- 降低tableView的高度。我得到了 tableView,它部分覆盖了屏幕,最后一行确实被遮挡了。
- 使用 contentSize - 将其高度设置为小而大的值 - 不走运。
- 设置
contentInset.bottom- 有效,但我在底部有一个无用的空间。 -
在
viewDidAppear中,照常处理99行并为第100行设置自定义contentOffset:offset.y += tableView_.contentSize.height - tableView_.bounds.size.height + 44;也有效,但它似乎是一种丑陋的方式。
那么,当“tableView-controller”出现时,我应该怎么做才能让我的 tableView 预滚动到第 100 个元素?
更新。 我不使用任何 xib 或故事板,只是在 viewDidLoad 中定义视图:
- (void)viewDidLoad {
[super viewDidLoad];
tableView_ = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
tableView_.dataSource = self;
tableView_.delegate = self;
tableView_.sectionFooterHeight = 0.0f;
self.view = tableView_;
numbers = [NSMutableDictionary dictionary];
numberSectionTitles = [NSMutableArray array];
//... some model initialization
headerView = [[UIView alloc] initWithFrame:(CGRect){0, 0, 320, 60}];
headerView.backgroundColor = [UIColor greenColor];
UILabel *l = [[UILabel alloc] initWithFrame:(CGRect){20, 20, 280, 20}];
l.textColor =[UIColor whiteColor];
l.tag = 121;
[headerView addSubview:l];
}
并在 viewDidAppear 中调整选择(肮脏的解决方法)
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
int row = _selectedIndex % 10;
int section = (_selectedIndex - row) / 10;
if(row == 9 && section == 9){
CGSize contentSize = tableView_.contentSize;
CGPoint offset = tableView_.contentOffset;
offset.y += tableView_.contentSize.height - tableView_.bounds.size.height + 44;
tableView_.contentOffset = offset;
}
[tableView_ selectRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section] animated:NO scrollPosition:UITableViewScrollPositionMiddle];
}
【问题讨论】:
标签: ios objective-c uitableview