[英]UITableView does not PROPERLY scroll to bottom programmatically
我有一個100行的表格,想要以編程方式將其滾動到任何元素,然后選擇該元素。 在第一個控制器中,我指定行和節,然后將帶有UITableView的控制器推入導航堆棧。 在“ tableView-controller”的viewWillAppear
,我使用以下代碼:
[tableView_ selectRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section] animated:NO scrollPosition:UITableViewScrollPositionMiddle];
有趣的是,它可以完美地滾動到99個第一行中的任何一個,第100行被選中,但仍在可見區域“下方”。 我必須手動滾動表格才能顯示它。
如果我將代碼放在viewDidAppear
,則表可以很好地滾動,但是會出現明顯的延遲。
我還嘗試了什么:
contentInset.bottom
,但底部沒有可用空間。 在viewDidAppear
,照常處理99行,並為第100行設置自定義contentOffset
:
offset.y += tableView_.contentSize.height - tableView_.bounds.size.height + 44;
也可行,但這似乎是一個丑陋的方式。
因此,當出現“ tableView-controller”時,如何使tableView預先滾動到第100個元素?
更新。 我不使用任何xibs或情節提要,僅在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];
}
可能是您的視圖高度與tableview不同。 您的superview(要在其上添加tableview)應該相同。 您的最后一行處於隱藏狀態,因為視圖的高度與表格視圖的高度不同,這也許可以解決您的問題。
您可以手動執行以下操作:
[_tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section] animated:NO scrollPosition:UITableViewScrollPositionNone];
CGRect rect = [_tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section]];
CGFloat offsetY = rect.origin.y+rect.size.height/2-_tableView.frame.size.height/2-_tableView.contentInset.top/2;
if (offsetY < -_tableView.contentInset.top)
offsetY = -_tableView.contentInset.top;
else if (offsetY > _tableView.contentSize.height-_tableView.frame.size.height)
offsetY = _tableView.contentSize.height-_tableView.frame.size.height;
_tableView.contentOffset = CGPointMake(_tableView.contentOffset.x, offsetY);
如果(cell == nil)
如果您在CellforRowatIndexpath中編寫了這樣的if語句,請刪除該特定的if語句並繼續。 那條線引起問題
享受編碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.