I'm attempting to position my UISearchBar directly under my UINavigationBar but I'm having issues where it's not appearing at all. I'm using iOS8's new searchController.
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
self.salesTableView.tableHeaderView = self.searchController.searchBar;
Currently I'm using that which correctly adds it to my UITableView header, but the issue with that is that it scrolls with the table which is not what I want. I want it above my tableview so it sticks instead and tried this but it seems to be gone now, unless I'm not using the right values?
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.frame = CGRectMake(0, 0, self.searchController.searchBar.frame.size.width, 44.0);
// self.salesTableView.tableHeaderView = self.searchController.searchBar;
Because the origin is (0,0), it will be hidden by status bar and navigation bar. You should see the search bar if changing to:
self.searchController.searchBar.frame = CGRectMake(0, 64, self.searchController.searchBar.frame.size.width, 44.0);
I have two solution. I will show you the easy way (you could also use storyboard): Create a UIView in your ViewController, named searchBarView
; Add self.searchController.searchBar
into the searchBarView
; Add searchBarView
to your ViewController.
UIView *searchBarView = CGRectMake(0, 64, self.searchController.searchBar.frame.size.width, 44);
[searchBarView addSubView:self.searchController.searchBar];
[self.view addSubView:searchBarView];
I assume that you setup search controller self.searchController.searchBar.sizeToFit()
in viewDidload. If it is the universal app, you need to add this method (at least in my case to make everything work):
- (void)viewDidLayoutSubviews {
// you could check
// if (IS_IPAD || (IS_IPHONE_6PLUS && UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)))
[self.searchController.searchBar sizeToFit];
}
This is my first answer on stackoverflow. Hope this help ^^.
Two things to check out:
Try setting
automaticallyAdjustsScrollViewInsets
tofalse
on yourUIViewController
. That should shift the subviews of your view controller's view to below the navigation bar.Use
searchFieldBackgroundPositionAdjustment
(available iOS 5+) to adjust the position of the search field inside of yourUISearchBar
Usage:
let searchBar = UISearchBar()
searchBar.searchFieldBackgroundPositionAdjustment = UIOffset(horizontal: 0, vertical: 10)
来源:https://stackoverflow.com/questions/26639791/position-uisearchbar-programmatically-using-uisearchcontroller