UISearchBar in navigationbar

前端 未结 5 1562
梦如初夏
梦如初夏 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: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];
        ...
    }
    

提交回复
热议问题