iOS UIButton添加点击声音和振动效果

新建一个button的基类继承UIButton

.h文件

#import <UIKit/UIKit.h>

@interface SWButton : UIButton

@end

.m文件

#import "SWButton.h"
#import <AudioToolbox/AudioToolbox.h>
@interface SWButton()
{
    SystemSoundID soundFileObject;
}
@end

@implementation SWButton

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event
{
    [self playSoundEffect:@"switch_click"type:@"mp3"];
    [super touchesBegan:touches withEvent:event];
}

- (void)playSoundEffect:(NSString*)name type:(NSString*)type
{
    //得到音效文件的地址
    NSString*soundFilePath =[[NSBundle mainBundle]pathForResource:name ofType:type];
    //将地址字符串转换成url
    NSURL*soundURL = [NSURL fileURLWithPath:soundFilePath];
    //生成系统音效id
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &soundFileObject);
    //播放系统音效
    AudioServicesPlaySystemSound(soundFileObject);
    //AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    AudioServicesPlaySystemSound(1519);
}
@end

相关推荐

微信扫一扫,分享到朋友圈

iOS UIButton添加点击声音和振动效果
返回顶部

显示

忘记密码?

显示

显示

获取验证码

Close