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
?
问题:
回答1:
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 aXYZTopView
)UINavigationController
(managing a private navigation view hierarchy defined by Apple)XYZFirstPageViewController
(managing aXYZFirstPageView
) (the “root” view controller)XYZSecondPageViewController
(managing aXYZSecondPageView
) (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)
回答2:
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):
- How to show a uiview alway on top?
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];