I was wondering how I would go about creating a view that persists through all the over views and controllers in the application. Similarly to how Soundcloud does it with their music player in their iPhone app (See pic). No matter where you go in the application the music player view stays at the top below the toolbar.
views:
38answers:
2You can add a view as a subview of your main window, and position it above your tabBarController's view. It will then always be visible.
The basic answer is to create a view at the top of the view hierarchy.
Let's take the example of your tab view-based screenshot above. Let's say the root view controller for the app is a subclass of UITabBarController
called RootViewController
.
Normally your application delegate will have a method that will look similar to this:
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
[window addSubview:rootViewController.view];
[window makeKeyAndVisible];
}
If you want your view to just "overlap", that's simple. Let's say you want your "persistent view" to be 100 pixels tall and stretch the width of the screen. Assume you've already created a class for this view, and it's called PeristentView. Your code would look something like this:
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
[window addSubview:rootViewController.view];
PersistentView* persistentView = [[PersistentView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
[window addSubview:persistentView];
[persistentView release];
[window makeKeyAndVisible];
}
The order here is important because you want the persistent view to be below in the view hierarchy, so that the rootViewController
's view
draws first, then the persistent view draws second.
If you want the persistent view to "push down" the the rest of the views on the screen, you'll have to change this up a bit. Given that by default you are telling the window to add the entirety of the root view controller's view as a subview, what you want to do instead is resize the frame
of rootViewController.view
so it doesn't take up the whole screen and reposition its origin
.
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
PersistentView* persistentView = [[PersistentView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
[window addSubview:persistentView];
[persistentView release];
CGRect frame = rootViewController.view.frame;
frame.size.height -= persistentView.frame.size.height;
frame.origin.y += persistentView.frame.size.height;
rootViewController.view.frame = frame;
[window addSubview:rootViewController.view];
[window makeKeyAndVisible];
}
I just tested this with an existing tab bar-based project (using a plain UIView
instead of creating a PersistentView class to bootstrap the test) and it works fine.