私はカテゴリを作成することをお勧めします。
私はこのよう続行:
.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];
iを構築する場合Interface Builderのnterfaceであれば、これはIBActionで実現するのが非常に簡単です。 –