1、首先给UIControl添加分类,#import "UIControl+controlTool.h"
分类的.h文件下
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
// 创建block
typedef void (^ActionBlock)(UIControl *control);
@interface UIControl (Button)
// 封装button的点击方法
- (void)addMethodBlock:(ActionBlock)actionBlock WithEvents:(UIControlEvents)controlEvents;
// 快速创建button并执行block中的点击方法
- (UIButton *)creatButtonWithFrame:(CGRect)frame backgroundColor:(UIColor *)backgroundColor title:(NSString *)title titleFont:(UIFont *)font actionBlock:(ActionBlock)actionBlock;
@end
2、UIControl分类的.m文件下
#import "UIControl+Button.h"
@implementation UIControl (Button)
// 静态变量
static char overview = 'a';
- (void)addMethodBlock:(ActionBlock)actionBlock WithEvents:(UIControlEvents)controlEvents{
///id object, const void *key, id value, objc_AssociationPolicy policy
objc_setAssociatedObject(self, &overview, actionBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(myAction) forControlEvents:controlEvents];
}
- (void)myAction{
ActionBlock block = (ActionBlock)objc_getAssociatedObject(self, &overview);
if (block) {
block(self);
}
}
- (UIButton *)creatButtonWithFrame:(CGRect)frame backgroundColor:(UIColor *)backgroundColor title:(NSString *)title titleFont:(UIFont *)font actionBlock:(ActionBlock)actionBlock
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = frame;
[button setBackgroundColor:backgroundColor];
[button setTitle:title forState:UIControlStateNormal];
button.titleLabel.font = font;
[button addMethodBlock:actionBlock WithEvents:UIControlEventTouchUpInside];
return button;
}
@end
3、 在任意控制器下创建button
#import "ViewController.h"
#import "UIControl+Button.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIControl *control = [[UIControl alloc] init];
UIButton *button = [control creatButtonWithFrame:CGRectMake(100, 100, 100, 100) backgroundColor:[UIColor redColor] title:@"test" titleFont:[UIFont systemFontOfSize:30] actionBlock:^(UIControl *control) {
NSLog(@"小民哥创建了一个button");
}];
[self.view addSubview:button];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
博客地址:http://blog.sina.com.cn/s/blog_c70304d60102x9ez.html
相关runtime使用:http://www.jianshu.com/p/0c9d21dba9e4
网友评论