UITabBar应用程序和按钮,用于在选项卡中播放音乐

时间:2009-02-22 03:47:36

标签: iphone

我在其中一个标签中运行了一个AVAudioPlayer实例。它通过IBAction激活。

我想在用户点击其他标签时停止播放音乐。

我将如何做到这一点?

我试过了theAudio.stop;在viewDidLoad中,但是没有用。

3 个答案:

答案 0 :(得分:0)

在你的UITabBarControllerDelegate中实现以下方法;

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController

只要用户在控制器中选择新视图,就会调用此方法。

我认为您还可以在播放音频的UIViewController中覆盖以下方法

-(void) viewDidDisappear:(BOOL)animated

答案 1 :(得分:0)

将UITabBarControllerDelegate连接到您的主视图,然后收听(void)tabBarController:(UITabBarController *)tabBarController didSelectItem:(UITabBarItem *)item

当你得到那个事件时,找到对象模型中的玩家并停止它。

答案 2 :(得分:0)

在尝试回答同样的问题时,我发现了这篇文章。为了防止其他人仍在寻找,我终于想出了如何使用NSNotificationCenter。基本上,NSNotificationCenter会向整个应用程序发送“广播”消息。如果“观察者”碰巧正在倾听,如下所示,将调用给定的方法。代码如下所示:

在您的App代表中:

    - (void)applicationDidFinishLaunching:(UIApplication *)application {

    // Add the tab bar controller's current view as a subview of the window
    [window addSubview:tabBarController.view];

    // Make sure you add this so that your tab bar calls its delegate methods
    tabBarController.delegate = self;
}

    // Optional UITabBarControllerDelegate method (this will be commented out by default - uncomment it)

    - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
                // Create the NSNotificationCenter
                [[NSNotificationCenter defaultCenter] postNotificationName:@"tabChanged" object:nil];
    }

在视图控制器中:

- (void)viewDidLoad {
    [super viewDidLoad];

    // Register an observer to stop audio recording/playing on tab change
    [[NSNotificationCenter defaultCenter] addObserver:self
                          selector:@selector(tabChanged)
                          name:@"tabChanged"
                          object:nil];
}

- (void)tabChanged {
        @"Received Notification!";
        if([player isPlaying]) {
            [player stop];
        }
}
相关问题