有没有办法创建一个在新闻事件中播放声音的自定义UIButton?

时间:2012-03-21 10:33:37

标签: audio ios5

我想在按下uibutton时关联声音效果。到目前为止,我已将方法与触碰事件相关联

 [allButton addTarget:self action:@selector(showAll) forControlEvents:UIControlEventTouchDownInside];

并在名为

的方法中调用播放声音方法
 - (void)showAll
{
    [self.buttonSoundEffect play];

    ...
}

有更好的方法吗?我可以继承UIButton类来处理声音效果,并为我的应用程序特定的每个按钮引用这个新的UIButton类吗?

1 个答案:

答案 0 :(得分:1)

我相信创建一个类别是可行的方法。

我这样做:

·H:

#import <UIKit/UIKit.h>

@class SCLSoundEffect;

typedef enum {
  SCLCLICKSOUND = 0,
  SCLOTHERSOUND,  
} SCLSoundCategory;


@interface UIButton (soundEffect)

@property (nonatomic, strong) SCLSoundEffect *buttonSoundEffect;


+ (id) buttonWithType:(UIButtonType)buttonType andSound: (SCLSoundCategory)soundCategory;
- (void) playSound;

@end

的.m:

#import "UIButton+soundEffect.h"
#import <objc/runtime.h>
#import "SCLSoundEffect.h"

static char const * const kButtonSoundEffectKey = "buttonSoundEffect";

@implementation UIButton (soundEffect)

@dynamic buttonSoundEffect;


+ (id) buttonWithType:(UIButtonType)buttonType andSound:(SCLSoundCategory) soundCategory;
{
    UIButton *newButton = [UIButton buttonWithType:buttonType];

    NSString *stringToUse = nil;

    switch (soundCategory) {
        case SCLCLICKSOUND:
            stringToUse = @"button_sound.wav";
            break;
        case SCLOTHERSOUND:
            assert(0); // To be defined

        default:
            break;
    }

    [newButton setButtonSoundEffect: [[SCLSoundEffect alloc] initWithSoundNamed:stringToUse]];
    [newButton addTarget:newButton action:@selector(playSound) forControlEvents:UIControlEventTouchDown];

    return newButton;
}


- (void) playSound
{
    [self.buttonSoundEffect play];
}


- (SCLSoundEffect *)buttonSoundEffect {
    return objc_getAssociatedObject(self, kButtonSoundEffectKey);
}

- (void)setButtonSoundEffect:(SCLSoundEffect *)buttonSoundEffect{
    objc_setAssociatedObject(self, kButtonSoundEffectKey, buttonSoundEffect, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void) dealloc
{
    [self setButtonSoundEffect:nil];
}

现在每次创建播放声音的按钮时,我只需要使用以下方法:

UIButton *mySoundButton = [UIButton buttonWithType:UIButtonTypeCustom andSound:SCLCLICKSOUND];