ios - 在每个 View Controller 中处理远程控制事件

标签 ios objective-c cocoa-touch

我的应用程序中有 2 个 ViewController。

ViewController1 播放音频,ViewController2 显示一些文本。

当我在 ViewController2 中时,我想使用 Remote 来控制音频。例如,用户在 ViewController2 中并想要停止音频。

我的代码:

ViewController1.m 完美运行

- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent
{
    MARK;
    if (receivedEvent.type == UIEventTypeRemoteControl) {

        switch (receivedEvent.subtype) {

            case UIEventSubtypeRemoteControlTogglePlayPause:
                DLog(@"remotecontrol_toggle");
                [self togglePlayPause];
                break;

            case UIEventSubtypeRemoteControlPause:
                DLog(@"remotecontrol_pause");
                [self pause];
                break;

            case UIEventSubtypeRemoteControlPlay:
                DLog(@"remotecontrol_play");
                [self play];
                break;

            case UIEventSubtypeRemoteControlStop:
                DLog(@"remotecontrol_stop");
                [self stop];
                break;

            default:
                break;
        }
    }
}

我的问题是,把这一切放在一起的最好方法是什么?我必须处理 ViewController2 中的事件吗?

我知道在 AppDelegate.m 中,我可以这样做:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    MARK;
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    MARK;
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
}

这样,我的应用程序在每个 View 中控制 Remote ,但这并不能解决我的问题,因为在 ViewController2 中没有处理接收到的事件。

但是我不能处理 AppDelegate.m 中收到的事件,所以我必须处理每个 ViewController 中的事件?

我是iOS开发的新手,不知道我是否在这里思考。

任何帮助表示赞赏。

最佳答案

最简单的方法是在创建 ViewController1 时将对 ViewController2 的引用传递给它。最简单的方法是有一个带有引用的 init 方法......

- (id) initWithController:(UIViewController*)controller
{
   self = [super init];
    if (self) {
        _controller1 = controller;
    }
    return self;
}

然后使用相同的方法接收事件,但调用 ViewController1 来处理它们......
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent
{

    if (receivedEvent.type == UIEventTypeRemoteControl) {

        switch (receivedEvent.subtype) {

            case UIEventSubtypeRemoteControlTogglePlayPause:
                DLog(@"remotecontrol_toggle");
                [self.controller1 togglePlayPause];
                break;

            // etc.
        }
    }
}

关于ios - 在每个 View Controller 中处理远程控制事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19595025/

相关文章:

ios - NSXMLParser 解析在 XML 文档中途中断

ios - 隐式转换丢失整数精度 : 'unsigned long' to 'int' - Error

ios - 如何将 Google MapView 放入 UIView 中?

ios - 将图像从 UIImageView 上传到 Parse.com

android - 如何填补7段字符每段之间的空白

iphone - UITableView 单元格重用、低内存警告、加载图像后设备中的应用程序崩溃

ios - 如何从My.Framework访问第三方框架?

objective-c - 将 UISwitch 添加到 UINavigationItem

cocoa-touch - 文件所有者到底是什么意思?

ios - 将 URL 列表从按钮提供给 WebView XCODE 4.5