UITableView contentOffSet is not working properly UITableView contentOffSet is not working properly ios ios

UITableView contentOffSet is not working properly

This worked for me:

// contentOffset will not change before the main runloop ends without queueing it, for iPad that isdispatch_async(dispatch_get_main_queue(), ^{    // The search bar is hidden when the view becomes visible the first time    self.tableView.contentOffset = CGPointMake(0, CGRectGetHeight(self.searchBar.bounds));});

Put it in your -viewDidLoad or -viewWillAppear

Not sure what the reason is (don't have time to research it right now), but I solved this issue by using performSelector after a delay of 0. Example:

- (void)viewWillAppear:(BOOL)animated {    ...    [self performSelector:@selector(hideSearchBar) withObject:nil afterDelay:0.0f];}- (void)hideSearchBar {    self.tableView.contentOffset = CGPointMake(0, 44);}

In earlier versions of the iOS SDK, methods such as viewWillAppear ran on the main thread, they now run on a background thread which is why the issue now occurs.

Most callbacks tend to fire on a background thread so always check for thread safety when doing UI calls.

Dispatch the change to the content offset on the main thread:

Objective C

dispatch_async(dispatch_get_main_queue(), ^{    CGPoint offset = CGPointMake(0, self.searchBar.bounds.height)    [self.tableView setContentOffset:offset animated:NO];});

Swift 3

DispatchQueue.main.async {            let offset = CGPoint.init(x: 0, y: self.searchBar.bounds.height)            self.tableView.setContentOffset(offset, animated: false)        }