简体   繁体   English

获取UITableView从底部/捕捉向上滚动到底部,而不是顶部

[英]Get a UITableView to scroll up from the bottom / snap to the bottom, not the top

I have a table view which is many cases will only have one or two cells that don't fill the screen. 我有一个表视图,很多情况下只有一个或两个单元格没有填满屏幕。 In this case, I would like the cells to sit at the bottom, rather than the top. 在这种情况下,我希望细胞位于底部,而不是顶部。 In other words they should "snap" to the bottom of the tableview. 换句话说,他们应该“捕捉”到桌面视图的底部。

I can force the table view to scroll them to the bottom like this: 我可以强制表视图将它们滚动到底部,如下所示:

  CGPoint bottomOffset = CGPointMake(0, [self.tableView contentSize].height - self.tableView.frame.size.height);
  [self.tableView setContentOffset:bottomOffset animated:NO];

However, this is only partially successful. 但是,这只是部分成功。 First, it doesn't work if I put it in viewDidLoad or viewWillAppear, only in viewDidAppear, which means that the user sees the tableview with the cells at the top first, then they move to the bottom. 首先,如果我将它放在viewDidLoad或viewWillAppear中,只有在viewDidAppear中才会起作用,这意味着用户首先看到顶部有单元格的tableview,然后它们会移到底部。 Second, if they scroll the table view, when they let go it automatically "snaps" back up to the top. 其次,如果他们滚动表格视图,当他们放开时,它会自动“捕捉”回到顶部。

Does anyone know how to change this behaviour? 有谁知道如何改变这种行为?

One option to consider is to resize the UITableView itself based on how many rows you will be displaying. 要考虑的一个选项是根据要显示的行数来调整UITableView本身的大小。 Presuming that your UITableViewDelegate implements heightForRowAtIndexPath one can then set the height of the UITableView in a viewWillAppear method by multiplying the number of rows by the height of each row. 假设您的UITableViewDelegate实现了heightForRowAtIndexPath,则可以通过将行数乘以每行的高度来设置viewWillAppear方法中UITableView的高度。

Something like this: 像这样的东西:

CGRect frame = [myTableView frame];

frame.size.height = [[myTableView dataSource] tableView: myTableView numberOfRowsInSection: 0] *
                    [[myTableView delegate] tableView: myTableView heightForRowAtIndexPath: [NSIndexPath indexPathForRow: 0 inSection: 0]];

[myTableView setFrame: frame];

This example assumes your table has one section and each row is the same height. 此示例假定您的表有一个部分,每行的高度相同。 Computing the size would have to get a little more complicated if multiple sections are involved or if different rows might be different heights. 如果涉及多个部分或者不同的行可能是不同的高度,则计算大小将变得更复杂。

Regardless of how the height is calculated the essence of the idea though is to just make the table itself shorter, no taller than the one or two rows that it is displaying, rather than trying to force it into behaving differently. 无论如何计算高度,这个想法的本质是让表本身更短,不比它显示的一两行高,而不是试图强迫它表现不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM