Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide UITableView search bar by default when in a navigation controller

I've read multiple posts on this but it's not working properly for me. I'm using the latest 4.2 SDK.

The code I have is

self.tableView.contentOffset = CGPointMake(0.0, 44.0);

This partially works, it moves the search bar up a little bit, but it does not get hidden completely. I've tried increasing the value 44 to something greater and this had no affect what so ever! I'm calling this code in the viewDidLoad method of the table's view controller. Does anyone have any ideas?

like image 919
Darthtong Avatar asked Nov 25 '10 01:11

Darthtong


1 Answers

Another approach should be...in viewDidLoad call:

self.tableView.contentInset = UIEdgeInsetsMake(-self.searchDisplayController.searchBar.frame.size.height, 0, 0, 0);

and implementing endDragging delegate method:

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    CGPoint offset = self.tableView.contentOffset;

    CGFloat barHeight = self.searchDisplayController.searchBar.frame.size.height;
    if (offset.y <= barHeight/2.0f) {
        self.tableView.contentInset = UIEdgeInsetsZero;
    } else {
        self.tableView.contentInset = UIEdgeInsetsMake(-barHeight, 0, 0, 0);
    }

    self.tableView.contentOffset = offset;
}

setting content is to remove some "flickering"

also if You want searchbar to stick at the top, implement didScroll this way:

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
     CGRect sbFrame = self.searchDisplayController.searchBar.frame;
     sbFrame.origin.y = self.tableView.contentOffset.y;
     if (sbFrame.origin.y > 0) {
         sbFrame.origin.y = 0;
     }
     self.searchDisplayController.searchBar.frame = sbFrame;
}

I hope this will help (took me few days to figure out:) )

Cheers!

UPDATE:

As @carbonr noted You should add this line in viewDidLoad since iOS7+

self.edgesForExtendedLayout = UIRectEdgeNone;
like image 56
JakubKnejzlik Avatar answered Sep 21 '22 15:09

JakubKnejzlik