【问题标题】:Is there a way to create a custom UIButton that play sound on press event?有没有办法创建一个自定义 UIButton 在按下事件时播放声音?
【发布时间】:2012-04-23 18:21:45
【问题描述】:

我想在按下 uibutton 时关联一个音效。到目前为止,我已经将一个方法与着陆事件相关联

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

并在被调用的方法中调用播放声音方法:

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

    ...
}

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

【问题讨论】:

  • 如果您在 Interface Builder 中构建界面,那么使用 IBAction 很容易实现。

标签: audio ios5


【解决方案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];

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-12-05
  • 2013-10-20
  • 1970-01-01
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
  • 2016-05-29
  • 1970-01-01
相关资源
最近更新 更多