gpt4 book ai didi

audio - 有没有一种方法可以创建一个自定义UIButton来在按下事件时播放声音?

转载 作者:行者123 更新时间:2023-12-03 00:59:52 26 4
gpt4 key购买 nike

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

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

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

...
}

有一个更好的方法吗?我可以对UIButton类进行子类化以处理声音效果,并为应用程序特定的每个按钮引用这个新的UIButton类吗?

最佳答案

我相信创建类别是一种方法。

我这样进行:

。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];

关于audio - 有没有一种方法可以创建一个自定义UIButton来在按下事件时播放声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9802787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com