每次使用UIButton的点击事件都要新写一个方法,感觉太麻烦,今天下来无事就用block封装了一下button的操作事件,这样以后能省下一些时间,而且代码量也减少了不少。
下面我写上源码:
我写的是UIButton的类目
h文件:
#import <UIKit/UIKit.h>
typedef void (^ActionBlock)();
typedef void (^Block_SureEvent)();
@interface UIButton (Block)<UIAlertViewDelegate>
-(void)handleClickEvent:(UIControlEvents)aEvent withClickBlick:(ActionBlock)buttonClickEvent;
-(void)AlertViewTitle:(NSString *)aTitle message:(NSString *)aMsg cancleButtonTitle:(NSString *)aButtonTitle sureButtonTitle:(NSString *)aSureButton sureBlockEvent:(Block_SureEvent)aSureEvent;
@end
下面是m文件
#import "UIButton+Block.h"
#import <objc/runtime.h>
static char *overViewKey;
@implementation UIButton (Block)
-(void)handleClickEvent:(UIControlEvents)aEvent withClickBlick:(ActionBlock)buttonClickEvent
{
objc_setAssociatedObject(self, &overViewKey, buttonClickEvent, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(buttonClick) forControlEvents:aEvent];
}
-(void)buttonClick
{
ActionBlock blockClick = objc_getAssociatedObject(self, &overViewKey);
if (blockClick != nil)
{
blockClick();
}
}
@end
其中要想使用关联对象的objc_setAssociatedObject和objc_getAssociatedObject必须引用头文件objc/runtime.h
objc_setAssociatedObject的四个参数分别为:源对象,key[必须是 static char类型],关联对象,关联方式【与修饰属性类似】
objc_getAssociatedObject的两个参数:源对象,key。通过这两个参数可以获取关联的对象。
--------------------------------AlertView----------------------Block-----------------------------------------
static char * alertKey;
-(void)AlertViewTitle:(NSString *)aTitle message:(NSString *)aMsg cancleButtonTitle:(NSString *)aButtonTitle sureButtonTitle:(NSString *)aSureButton sureBlockEvent:(Block_SureEvent)aSureEvent
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:aTitle message:aMsg delegate:self cancelButtonTitle:aButtonTitle otherButtonTitles:aSureButton, nil];
objc_setAssociatedObject(self, &alertKey, aSureEvent, OBJC_ASSOCIATION_COPY_NONATOMIC);
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1)
{
Block_SureEvent blockSure = objc_getAssociatedObject(self, &alertKey);
if (blockSure != nil)
{
blockSure();
}
else
{
NSLog(@"error");
}
}
}