runtime应用一例

来源:互联网 发布:java图形化界面开发 编辑:程序博客网 时间:2024/05/18 01:37

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

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

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


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

- (void)sendAction:(SEL)action to:(nullableid)target forEvent:(nullableUIEvent *)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




0 0
原创粉丝点击