UISearchBar in navigationbar

前端 未结 5 1521
梦如初夏
梦如初夏 2020-11-27 14:16

How can I show a UISearchBar in the NavigationBar?

I can\'t figure out how to do this.

Your help is very much appreciated.

相关标签:
5条回答
  • 2020-11-27 15:07

    Objective C code snippet

    - (void)viewDidLoad {
        UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    
        if (@available(iOS 11.0, *)) {
            self.navigationItem.searchController = searchController;
        } else {
            self.navigationItem.titleView = searchController.searchBar;
        }
    }
    

    Read more here

    0 讨论(0)
  • 2020-11-27 15:11

    As of iOS 7, the UISearchDisplayController supports this by default. Set the UISearchDisplayController's displaysSearchBarInNavigationBar = YES to get this working easily.

    Per the documentation:

    Starting in iOS 7.0, you can use a search display controller with a navigation bar (an instance of the UINavigationBar class) by configuring the search display controller’s displaysSearchBarInNavigationBar and navigationItem properties.

    0 讨论(0)
  • 2020-11-27 15:12

    To put searchBar into the center of navigationBar:

    self.navigationItem.titleView = self.searchBarTop;
    

    To put searchBar to the left/right side of navigationBar:

    UIBarButtonItem *searchBarItem = [[UIBarButtonItem alloc] initWithCustomView:searchBar];
    self.navigationItem.rightBarButtonItem = searchBarItem;
    
    0 讨论(0)
  • 2020-11-27 15:16

    As one commenter noted, using searchDisplayController.displaysSearchBarInNavigationBar = true ends up hiding any existing left/right bar button items.

    I've found two different ways of adding a searchBar to a navigationBar using iOS7's new property on searchDisplayController.

    1) Nib Based Approach

    If you're using a .xib, you can set a User Defined Runtime Attribute for this value and for whatever reason, the leftBarButtonItem stays in tact. I have not tested it with a rightBarButtonItem.

    enter image description here

    2) Code (Timing Matters)

    If you want to implement in code, timing seems to matter. It seems that you must add the searchBar to the navigationBar first, then set your barButtonItem.

    - (void)viewDidLoad
    {
        ...
        self.searchDisplayController.displaysSearchBarInNavigationBar = true;
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem new];
        ...
    }
    
    0 讨论(0)
  • 2020-11-27 15:16

    Check out Apple's UICatalog sample code. It shows how to use the new UISearchController in three different ways: modally, in nav bar, and below the navigation bar.

    0 讨论(0)
提交回复
热议问题