Position UISearchBar programmatically using UISearchController

僤鯓⒐⒋嵵緔 提交于 2019-12-06 17:27:20

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:

  1. Try setting automaticallyAdjustsScrollViewInsets to false on your UIViewController. That should shift the subviews of your view controller's view to below the navigation bar.

  2. Use searchFieldBackgroundPositionAdjustment (available iOS 5+) to adjust the position of the search field inside of your UISearchBar


Usage:

let searchBar = UISearchBar()
searchBar.searchFieldBackgroundPositionAdjustment = UIOffset(horizontal: 0, vertical: 10)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!