Same UISearchBar for entire app?

2019-06-09 10:47发布

I've seen a lot of apps that have a universal search bar that always remains at the top of the app. I have implemented a UISearchBar with a UITableView in one view controller. I want to have the same search bar on other view controllers in my app. How do I link these other UISearchBars to the one I have already created? I.e., how do I configure these other UISearchBars so that they return the same search results and link to the same UITableView?

2条回答
Rolldiameter
2楼-- · 2019-06-09 11:05

Since you only every have one window per app, and view's don't have levels, you have to make sure that view stays on top of the hierarchy, no matter what. One relatively easy way is to add it directly to the window above the rest of the interface (the navigation controller):

In applicationDidLaunch:

// After the main navigation controller or tab controller has been added
// either programmatically or in the xib:
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0,70,320,44)];
[self.window addSubview:searchBar];
查看更多
霸刀☆藐视天下
3楼-- · 2019-06-09 11:17

Nested view controllers may be what you need.

Define a “top view controller” that manages a “top view” containing a search bar and add your (table) views to the top view (using -addSubview: on the top view) and the associated view controller(s) to the top view controller (using -addChildViewController: in the top VC and on itself).

In Interface Builder, you can define a top view and inside it a “container view.” The system then handles the insertion of the subview and sub-view controller.

By defining a good view controller hierarchy, you make your app design more logical and clean. I’d recommend to take some time into investigating a good hierarchy before diving into coding.

A final note: the UISearchDisplayController is an object (apparently not a view controller) that superimposes a search bar above a view controller’s view. You might be able to simply apply it immediately above the top-most view controller (the one that is always visible, like a navigation controller). It’s worth looking into it, if you didn’t already. ;-)


An example

View controller hierarchy

  • XYZTopViewController (managing a XYZTopView)
    • UINavigationController (managing a private navigation view hierarchy defined by Apple)
      • XYZFirstPageViewController (managing a XYZFirstPageView) (the “root” view controller)
      • XYZSecondPageViewController (managing a XYZSecondPageView) (pushed by nav. controller when you need it to)

View hierarchy

  • XYZTopView
    • UISearchBar
      • (private navigation view hierarchy defined by Apple)
      • XYZFirstPageView
        • (your view hierarchy belonging to the first page/screen)
查看更多
登录 后发表回答