让UIViewController成为单身人士? [英] Make UIViewController a singleton?

查看:92
本文介绍了让UIViewController成为单身人士?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用我的应用程序期间,用户应该能够启动,停止,转发背景音乐。 (跨越几个UIViewControllers)。为此,我使我的MusicPlayer成为单身( NSObject )。如果我在每个视图中为自己创建控件它可以工作,但我想要的基本上是一个视图来处理音乐播放器类并且一直存在。用户还应该能够通过向左或向右滑动来隐藏和显示视图。因此,如果它被隐藏并且我更改了我的视图控制器,它也应该隐藏在新视图控制器中,并且不应该中断音乐。

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.

什么是最好的方法得到这个?

What is the best approach to get to this?

谢谢

编辑:

嗯......我在我的家庭视图控制器中尝试了这个,它可以工作:

Well ... 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];

但是:

有没有办法在ApplicationDelegate中执行此操作?

Is there a way to do this in the ApplicationDelegate?

推荐答案

如果您的单身MusicPlayer正在播放音乐,那么它视图更改时不应中断。而不是为每个视图控制器创建音乐控件,您可以将音乐控件视图添加为窗口的子视图,并确保它保持在其他所有内容之上。

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.

更新:
在您的应用程序委托中,您通常需要一些代码来设置主视图(即applicationDidFinishLaunching方法)。我假设您有一个主导航或标签控制器,您可以在其中执行其他所有操作。因此,在将其视图添加到窗口后,创建并添加音乐播放器控制器视图并将其添加为窗口的子视图。只要您不向窗口添加其他视图,它就会保持在最顶层(如果这样做,您只需要将音乐控件移回到顶部)。

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).

我会使用一个单独的MusicPlayerController视图控制器,它拥有音乐播放器控件视图。这样,其他视图控制器可以轻松显示或隐藏控件。

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.

这篇关于让UIViewController成为单身人士?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆