Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

ios - Make UIViewController a singleton?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...