runtime应用一例

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

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

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


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

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


代码:

#import 
#import 

@interface UIButton(PlaySound)

@end

#import "ButtonPlaySound.h"
#import
#import 

@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




你可能感兴趣的:(ObjC,iOS)