Make UIViewController a singleton?

2019-01-28 01:01发布

During the use of my app, the user should be able to start, stop, forward background music. (Across several UIViewControllers). For this, I made my MusicPlayer a singleton (NSObject). If I create the controls in every view for itself it works, but what I want is basically one view which handles the music player class and is present all the time. The user also should be able to "hide" and "show" the view by swiping it to the left or to the right. So if it is hidden and I change my view Controller it should be hidden in the new view Controller too and the music should not be interrupted.

I tried this one 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 the ApplicationDelegate?

3条回答
【Aperson】
2楼-- · 2019-01-28 01:29

You can't : How to add button to UINavigationController

"Add UIbarButtonItem on the UIViewController not not on the UINavigationController. The navigation controller displays the navigation item of the top viewVontroller, not itself."

查看更多
在下西门庆
3楼-- · 2019-01-28 01:32

If you use a container view controller (e.g. UINavigationController), you then have all the view controllers switching between one another, and on top of the container you can add your MusicPlayer controls (easiest way would be for it to have the same parent as the navigation controller), that way it's created only once and it doesn't depend on what views are displayed under it.

查看更多
Deceive 欺骗
4楼-- · 2019-01-28 01:34

If your singleton MusicPlayer is playing the music, then it should not be interrupted when the view changes. And instead of creating music controls for every view controller, you could add the music controls view as a subview of the window and make sure that it stays on top of everything else.

Update: In your application delegate, you typically have some code to set up the main view (i.e. the applicationDidFinishLaunching method). I assume that you have a primary navigation or tab controller in which you do everything else. So after adding its view to the window, create and add your music player controller view and add it as a subview of the window. It will remain on top as long as you don't add other views to the window (if you do, you just need to move the music controls back to the top).

I would use a singleton MusicPlayerController view controller which owns the music player controls view. That way, other view controllers can easily show or hide the controls.

查看更多
登录 后发表回答