Strange behavior on scroll UITableView

2019-09-15 17:46发布

I have a single view with nested scroll and table view with this hierarchical tree:

Tree of the view

(The table is loaded with some Huckleberry Finn rows taken from this example.)

On viewWillAppear I programmatically scroll the Table View at the last row doing

-(void)viewWillAppear:(BOOL)animated
{
   [self.tableView reloadData];
   NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.tableView numberOfRowsInSection:0]-1 inSection:0];
   [self.tableView scrollToRowAtIndexPath:indexPath
                      atScrollPosition:UITableViewScrollPositionBottom
                              animated:YES];
}

and everything works as expected, in both orientation. As you can see, the text is rightly truncated.

portrait landscape

I've uploaded on Github my project so you can see it running. Download it here.

Now, if you add this line in the cellForRowAtIndexPath method:

cell.textLabel.numberOfLines=0;

the cells automatically will resize to embed and show the entire text label:

numberOfLines=0

BUT, and this is the issue my dear friends, as you can see the table is not scrolled to the last row but 5-6 rows above. And I cannot understand why.

The same thing happens also if NumberOfLines is 2,3 and so on. Only a value of 1 can make the TableView move down to the very last row.

(FYI, I do not use [self.tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)]; in order to scroll down the table because it throws an exception)

Maybe something is wrong with iOS8 ?

2条回答
家丑人穷心不美
2楼-- · 2019-09-15 18:18

I added this event with reloadSection method and now the table scroll to the end. Also, I changed "tableView" to "myTableView" since I read that is better to give a non-default name to the views (as Sapi says in his answer here).

- (void)viewDidLayoutSubviews {

    [self.myTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.myTableView numberOfRowsInSection:0]-1 inSection:0];
    [self.myTableView scrollToRowAtIndexPath:indexPath
                      atScrollPosition:UITableViewScrollPositionBottom
                              animated:YES];
}

IMHO this thing is very Machiavellian, however.

查看更多
做自己的国王
3楼-- · 2019-09-15 18:25

viewDidLayoutSubviews will do the job

I guess you use some autolayout or self sizing cells? In viewWillAppear the calculation is not finished. So you scroll to the bottom, but then thereafter autolayout resizes your cells what makes them expand in height.

For Details: Refer to apple documentation UIViewController

... "Your view controller can override this method to make changes after the view lays out its subviews. The default implementation of this method does nothing."

- (void)viewDidLayoutSubviews {
    // your code here
}
查看更多
登录 后发表回答