runtime应用一例

14 篇文章 0 订阅

看到有人在论坛问:自己的应用已经开发完了,老板突然说想让应用中的button点击时要带震动效果。

手机震动直接调用 AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);即可

但是如果要把这句话一个一个的加到所有but的点击回调方法里,未免工作量太“大”了,而且也比较“笨”,我想了想,觉得利用runtime机制,可以比较好的解决这个问题


首先要了解,UIButton继承自UIControl,点击but时会调用

- (void)sendAction:(SEL)action to:(nullable id)target forEvent:(nullable UIEvent *)event;方法


代码:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface UIButton(PlaySound)

@end

#import "ButtonPlaySound.h"
#import<objc/runtime.h>
#import <AudioToolbox/AudioToolbox.h>

@implementation UIButton(PlaySound)

+(void)load
{
    Method originalMethod = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
    Method myMethod = class_getInstanceMethod(self, @selector(mySendAction:to:forEvent:));
    //用自己的mySendAction方法,与sendAction方法进行交换
    method_exchangeImplementations(originalMethod, myMethod);
}

//交换后,点击but会调用mySendAction
- (void)mySendAction:(SEL)action to:(nullable id)target forEvent:(nullable UIEvent *)event
{
    //震动
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    //此处调用mySendAction,实际调用的是sendAction
    [self mySendAction:action to:target forEvent:event];
}


@end




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值