How to get a UITableview to go to the top of page on reload?

前端 未结 13 1895
一个人的身影
一个人的身影 2021-02-01 02:30

I am trying to get a UITableview to go to the top of the page when I reload the table data when I call the following from

- (void)pickerView:(UIPickerView *)pic         


        
13条回答
  •  醉梦人生
    2021-02-01 02:48

    WITHOUT ANIMATION

    I'm on iOS11, using a plain tableview style with sticky headers and somehow the only way I got this to work correctly to have the tableview really on top after a reload without any strange flickers/animation behaviours was to use these methods in this order where ALL of these are necessary:

    [self.tableView setContentOffset:CGPointZero animated:NO];
    [self.tableView reloadData];
    [self.tableView layoutIfNeeded];
    [self.tableView setContentOffset:CGPointZero animated:NO];
    

    I'm serious that all of these are necessary, even though it seems the first line is not relevant at all. Oh yeah, also very important, do NOT use this:

    self.tableView.contentOffset = CGPointZero;
    

    You would think that it's the same as the "setContentOffset animated:FALSE" but apparently it's not! Apple treats this method differently and in my case this only worked when using the full method with animated:FALSE.

    WITH ANIMATION

    I also wanted to try this with a nice scrolling animation to the top. There the content offset methods seemed to still cause some strange animation behaviours. The only way I got this working with a nice animation after some trial and error were these methods in this exact order:

    [self.tableView reloadData];
    [self.tableView layoutIfNeeded];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:TRUE];
    

    Warning, make sure you have at least 1 row before running the last line of code to avoid crashing :)

    I hope this helps someone someday!

提交回复
热议问题