不管在什么项目中总会有一些控件,它们样式相似却根据不同场景又有所不同。虽然也写了一些便利构造函数来快速的创建一些控件,但总感觉不尽人意,想用更少的代码来创建它们。
所以想到了链式语法,在查询部分资料和尝试后有了这篇日记。
直接百度的参考文章:
简书链接
作者的总结很精髓
首先获得实例中的一个block,然后执行block并返回实例本身,然后再执行实例的另一个block,而在这个block中同样返回实例本身,按此规律通过点语法一直往下执行。
接着我试着写了一个简单的可以用于快速创建UIButton的类:
.h文件内容
// Created by chizheng on 2017/6/20.
// Copyright © 2017年 yg-technology. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface CHZButton : UIButton
@property (nonatomic, copy) CHZButton * (^setTitle)(NSString *,UIControlState);
@property (nonatomic, copy) CHZButton * (^setTitleColor)(UIColor *,UIControlState);
@property (nonatomic, copy) CHZButton * (^setFont)(CGFloat);
@property (nonatomic, copy) CHZButton * (^setBackgroundColor)(UIColor *);
@property (nonatomic, copy) CHZButton * (^setCornerRadius)(CGFloat);
@property (nonatomic, copy) CHZButton * (^setImage)(NSString *,UIControlState);
@property (nonatomic, copy) CHZButton * (^addAction)(id,SEL,UIControlEvents);
@end
// Created by chizheng on 2017/6/20.
// Copyright © 2017年 yg-technology. All rights reserved.
//
#import "CHZButton.h"
@implementation CHZButton
- (CHZButton * (^)(NSString * title,UIControlState state))setTitle{
return ^(NSString * title,UIControlState state){
[self setTitle:title forState:state];
return self;
};
}
- (CHZButton * (^)(UIColor * titleColor,UIControlState state))setTitleColor{
return ^(UIColor * titleColor,UIControlState state){
[self setTitleColor:titleColor forState:state];
return self;
};
}
- (CHZButton * (^)(CGFloat font))setFont{
return ^(CGFloat font){
self.titleLabel.font = [UIFont systemFontOfSize:font];
return self;
};
}
- (CHZButton * (^)(UIColor * backgroundColor))setBackgroundColor{
return ^(UIColor * backgroundColor){
[self setBackgroundColor:backgroundColor];
return self;
};
}
- (CHZButton * (^)(CGFloat cornerRadius))setCornerRadius{
return ^(CGFloat cornerRadius){
self.layer.cornerRadius = cornerRadius;
self.clipsToBounds = YES;
return self;
};
}
- (CHZButton * (^)(NSString * imageName,UIControlState state))setImage{
return ^(NSString * imageName,UIControlState state){
[self setImage:[UIImage imageNamed:imageName] forState:state];
return self;
};
}
- (CHZButton * (^)(id target,SEL selector,UIControlEvents events))addAction{
return ^(id target,SEL selector,UIControlEvents events){
[self addTarget:target action:selector forControlEvents:events];
return self;
};
}
@end
创建按钮时只需要如下代码
CHZButton * btn = [CHZButton new];
btn.frame = CGRectMake(Margin_leading, 64, screenW-2*Margin_leading, 44);
btn.setFont(18).setTitle(@"测试按钮", UIControlStateNormal).setBackgroundColor(btn_Color).setCornerRadius(4);
btn.addAction(self, @selector(btnAction:), UIControlEventTouchUpInside);
[self.view addSubview:btn];
网友评论