In viewWillAppear
, I have added UISearchBar
as my headerview of UITableView
. When view loads, I hides UISearchbar
under <
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);
}
The problem may be with the search bar size. Try the following line of code.
[searchBar sizeToFit];
The line of code is working as it should.
Explaination of contentOffset
of a UITableView
:
For example, if you have a table view of height 100. Its content may be more than it's view, say 150. contentOffset
will tell the table from where in the content to start from. Say contentOffset = (0, 40)
, the content will be shown after 40 of it's height.
Note: Once the content is scrolled, there is no affect of the previously set contentOffset
.
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)
}
This worked for me.
self.tableView.beginUpdates()
self.tableView.setContentOffset( CGPoint(x: 0.0, y: 0.0), animated: false)
self.tableView.endUpdates()
Objective-C :
[_tableView beginUpdates];
[_tableView setContentOffset:CGPointMake(0, 0)];
[_tableView endUpdates];
This worked for me:
// contentOffset will not change before the main runloop ends without queueing it, for iPad that is
dispatch_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