将UISwitch与其他视图控制器中的事件连接

时间:2014-12-05 19:51:09

标签: ios

我有2个视图控制器,第一个是主视图控制器,当视图控制器加载时将运行音乐,而另一个视图控制器是内容为UISwitch的设置所以我想要的是当用户转到设置视图控制器并转向时关闭然后音乐将在主视图中停止 这是代码

main.h

#import<AVFoundation/AVAudioPlayer.h>

@interface main : UIViewController
{

AVAudioPlayer *audioPlayer;
BOOL didInitialize;

}

的main.m

static BOOL didInitialize = NO;
if (didInitialize == YES)
return;
didInitialize = YES;
//Add Audio Sound to the current View Controller
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/MLGBoxSoundTrack.mp3", [[NSBundle mainBundle] resourcePath]]];

NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1; // -1 for looping forever

//    audioPlayer.volume = 0.5; // 0.0 - no volume; 1.0 full volume
//    NSLog(@"%f seconds played so far", audioPlayer.currentTime);
//    audioPlayer.currentTime = 5; // jump to the 10 second mark
//    [audioPlayer pause];
//    [audioPlayer stop]; // Does not reset currentTime; sending play resumes

if (audioPlayer == nil)
{
    NSLog(@"No Audio Player");
}
else
{
    [audioPlayer play];
}
//End Audio Sound

1 个答案:

答案 0 :(得分:0)

Use NSNotificationCenter

第一个视图控制器,添加交换机通知观察器,切换开关时第二个视图控制器发布通知。