UItableview scrollToRowAtIndexPath not displaying last row correctly

后端 未结 2 1940
迷失自我
迷失自我 2021-01-13 20:43

I have a tableview with custom cells with dynamic cell heights depending on the cell content.

My problem is the following, when I ask, programmatically, in the viewD

2条回答
  •  渐次进展
    2021-01-13 21:32

    [self.tableView reloadData];
    dispatch_async(dispatch_get_main_queue(), ^{
            NSIndexPath *rowIndexPath = [NSIndexPath indexPathForRow:3 inSection:0];
            [self.tableView scrollToRowAtIndexPath:rowIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    });
    

    I don't know exactly why, but I guess this approach works because when we add(???) rows and call [tableView reloadData] tableView has no time to update some internal counters (like row counter) and calling [tableView scrollToRowAtIndexPath ...] has no effect since there is no such row at that time (again, probably correct in case you add rows or set tableView's data for the first time). Calling

    dispatch_async(dispatch_get_main_queue(), ^{
        ...
    }); 
    

    after [tableView reloadData] gives tableView enough time to update row counter and perform scroll to existing row.

    Vishy's approach works just because it gives enough time but applicable only if you need to scroll exactly one time when screen is loaded. Moreover it requires ugly flag to check every time viewDid/WillAppear.

提交回复
热议问题