如何设置回调函数?

时间:2014-11-14 20:57:48

标签: ios callback ios8 xcode6

我被困在这一段时间了。所以在我的应用程序中,我将有按钮播放声音。当用户点击按钮(button1.png)时,我想将图像更改为(button2.png),然后当声音播放完毕后,我想将图片pic更改为原始图像。我认为回调最好是设置它但我遇到麻烦。帮助将得到赞赏。

这是我的代码

#import "ViewController.h"
#import <AudioToolbox/AudioToolbox.h>

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[scrollView setScrollEnabled:YES];
// change setContentSize When making scroll view Bigger and adding more items
[scrollView setContentSize:CGSizeMake(320, 1000)];  

}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

#pragma mark - CallBackMethods









#pragma mark - SystemSoundIDs
SystemSoundID sound1;







#pragma mark - Sound Methods
-(void)playSound1
{
 NSString* path = [[NSBundle mainBundle]
                  pathForResource:@"Sound1" ofType:@"wav"];
NSURL* url = [NSURL fileURLWithPath:path];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &sound1);


static void (^callBAck)(SystemSoundID ssID, void *something);

callBAck = ^(SystemSoundID ssID, void *something){
    [button1 setImage:@"WhiteButton.png" forState:UIControlStateNormal];
};

 AudioServicesAddSystemSoundCompletion(sound1,
                                      NULL,
                                      NULL,
                                      callback,
                                      NULL);

AudioServicesPlaySystemSound(sound1);
}
- (IBAction)button:(id)sender {
NSLog(@"Hello");
[button1 setImage:[UIImage imageNamed:@"ButtonPressed.png"] forState:UIControlStateNormal];
[self playSound1];    
}
@end

1 个答案:

答案 0 :(得分:0)

AudioToolbox C 框架(请注意 C 样式函数调用)。 因此,您传递给它的回调必须是C function pointer

查看您需要传入的AudioServicesSystemSoundCompletionProc类型作为回拨的AudioServicesAddSystemSoundCompletion的第4个参数:

typedef void (*AudioServicesSystemSoundCompletionProc) ( SystemSoundID ssID, void *clientData );

它告诉您需要声明一个接受两个参数的 C函数并返回void作为回调处理程序并将其传递给AudioServicesAddSystemSoundCompletion

// Declare this anywhere in the source file.
// I would put this before @implement of the class.
void audioCompletionHandler(SystemSoundID ssID, void *clientData) {
    NSLog(@"Complete");
}

...

- (void)playSound {
    ...
    // To pass the function pointer, add & before the function name.
    AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, &audioCompletionHandler, NULL);
    AudioServicesPlaySystemSound(sound);
}