2012-03-21 6 views
0

uibuttonを押したときにサウンドエフェクトを関連付けたいと思います。これまでのところ、私はタッチダウンイベントプレスイベントでサウンドを再生するカスタムUIButtonを作成する方法はありますか?

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

にメソッドを関連付けると呼ばれるメソッド内で再生音のメソッドを呼び出しています

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

    ... 
} 

これを行うには良い方法はありますか?サウンドエフェクトを処理するためにUIButtonクラスをサブクラス化することはできますか?そして、この新しいUIButtonクラスを自分のアプリケーションに固有の各ボタンについて参照できますか?

+0

iを構築する場合Interface Builderのnterfaceであれば、これはIBActionで実現するのが非常に簡単です。 –

答えて

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]; 
+0

ここでSCLSoundEffectの実装を見つけることができます。http://stackoverflow.com/questions/9791491/best-way-to-play-simple-sound-effect-in-ios/9802540#9802540 – tiguero

関連する問題