iOS 用runtime给UIControl添加类别,并快速创建Button

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容