Make UIViewController a single?

While using my application, the user should be able to start, stop, forward background music. (Via several UIViewControllers). For this, I made MusicPlayer a singleton ( NSObject ). If I create controls in each view for myself, it works, but I want basically one view that processes the music player class and is present all the time . The user should also be able to "hide" and "show" the view by swiping it left or right. Therefore, if it is hidden, and I change my view controller, it must be hidden in the new view controller, and the music should not be interrupted.

I tried this in my home view controller and it works:

 UIView * playerView = [[UIView alloc] initWithFrame:CGRectMake(0, 300, self.view.bounds.size.width, 44)]; playerView.backgroundColor = [UIColor redColor]; [[[[UIApplication sharedApplication] delegate] window] addSubview:playerView]; 

Is there a way to do this in ApplicationDelegate?

+6
source share
3 answers

If your single-user MusicPlayer is playing music, it should not be interrupted when the presentation changes. Instead of creating music controls for each view controller, you can add a musical control view as a subview of the window and make sure that it stays on top of everything else.

Update: In application deletion, you usually have some code to configure the main view (i.e., the applicationDidFinishLaunching Method). I assume that you have a main navigation or tab controller in which you do the rest. Therefore, adding your view to the window, create and add a view of the controller of the music player and add it as a subspecies of the window. It will stay on top until you add other views to the window (if you do, you just need to move the music controls up).

I would use one MusicPlayerController view control that owns a music player control. In this way, other view controllers can easily show or hide controls.

+6
source

If you use a container view controller (for example, UINavigationController), then you have all the view controllers switching among themselves, and on top of the container you can add MusicPlayer controls (it would be easiest to have the same parent as the navigation controller), thus it is created only once and does not depend on which views are displayed under it.

0
source

You cannot: How to add a button to a UINavigationController

"Add a UIbarButtonItem to the UIViewController, not to the UINavigationController. The navigation controller displays the navigation element of the top viewVontroller, not itself.

0
source

Source: https://habr.com/ru/post/911512/


All Articles