从每个视图控制器调用方法

时间:2016-08-17 11:51:55

标签: ios iphone

我想从每个视图控制器调用此方法。但我不知道这个方法将在哪里写,以及我如何调用此方法。

-(void)playSound{

NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]];
NSData *data =[NSData dataWithContentsOfURL:url];
audioPlayer  = [[AVAudioPlayer alloc] initWithData:data error:nil];
audioPlayer.delegate = self;
[audioPlayer setNumberOfLoops:0];
[audioPlayer play];
}

3 个答案:

答案 0 :(得分:2)

您可以创建一个BaseViewController并在BaseViewController.h中声明此方法,并在BaseViewController.m文件中实施,而不是将所有ViewController设置为BaseViewController的子项

<强> BaseViewController.h

@interface BaseViewController : UIViewController

-(void)playSound;

@end

<强> BaseViewController.m

@interface BaseViewController ()

@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

}

-(void)playSound {
     NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]];
     NSData *data =[NSData dataWithContentsOfURL:url];
     audioPlayer  = [[AVAudioPlayer alloc] initWithData:data error:nil];
     audioPlayer.delegate = self;
     [audioPlayer setNumberOfLoops:0];
     [audioPlayer play];
}
@end

现在在 viewController.h

@interface ViewController : BaseViewController

@end

<强> ViewController.m

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self playSound];
}
@end

答案 1 :(得分:2)

您可以创建一个类别:

@interface UIViewController (UIViewControllerAudio)

-(void)playSound;

@end


@implementation UIViewController (UIViewControllerAudio)

- (void)playSound{
    NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]];
    NSData *data =[NSData dataWithContentsOfURL:url];
    audioPlayer  = [[AVAudioPlayer alloc] initWithData:data error:nil];
    audioPlayer.delegate = self;
    [audioPlayer setNumberOfLoops:0];
    [audioPlayer play];
}

@end

您可以在视图控制器中调用:

[self playSound];

答案 2 :(得分:2)

<强>步骤1

创建一个BaseViewController

@interface BaseViewController : UIViewController

 - (void) playSound;

 @end

<强>步骤-2

BaseViewController.m

@implementation BaseViewController

-(void)playSound{

NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]];
NSData *data =[NSData dataWithContentsOfURL:url];
audioPlayer  = [[AVAudioPlayer alloc] initWithData:data error:nil];
audioPlayer.delegate = self;
[audioPlayer setNumberOfLoops:0];
[audioPlayer play];
}

@end

<强>步骤-3

  #import "BaseViewController.h"

// Notice this class is a subclass of BaseViewController (parent)
@interface yourViewController : BaseViewController
@end

步骤-4

你可以直接打电话

- (void)viewDidLoad
{
[super viewDidLoad];
 [self playSound];
}