iOS中链式编程最有名的莫过于Masonry了,以前就觉得Masonry的语法很好看,简单清楚明了,担得起“优雅”二字,那么这种链式编程的方法如何实现呢?在查询资料后,找到了一个小哥提供的案例,代码一眼就能让你了解链式编程。
先说理论,链式编程的特色在于连续的.
语法,实现它,可以借助于Block
:
利用类的getter
特性,使得方法返回一个Block
Block
中执行指定操作,并且返回该类的实例变量,以此实现连续的.
语法
代码一看就会很清晰:
// UIButton+JWExtension.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIButton (JWExtension)
+ (UIButton *)button;
// 设置默认状态标题
- (UIButton *(^)(NSString *))normalTitle;
// 设置选中状态标题
- (UIButton *(^)(NSString *))selectedTitle;
// 设置高亮状态标题
- (UIButton *(^)(NSString *))highlightTitle;
// 设置普通状态图片
- (UIButton *(^)(UIImage *))normalImage;
// 设置选中状态图片
- (UIButton *(^)(UIImage *))selectedImage;
// 设置高亮状态图片
- (UIButton *(^)(UIImage *))highlightedImage;
// 设置普通状态背景图片
- (UIButton *(^)(UIImage *))normalBackgroundImage;
// 设置高亮状态背景图片
- (UIButton *(^)(UIImage *))highlightedBackgroundImage;
// 设置选中状态背景图片
- (UIButton *(^)(UIImage *))selectedBackgroundImage;
@end
// UIButton+JWExtension.m
#import "UIButton+JWExtension.h"
@implementation UIButton (JWExtension)
+ (UIButton *)button{
return [self buttonWithType:UIButtonTypeCustom];
}
- (UIButton * _Nonnull (^)(NSString * _Nonnull))normalTitle{
return ^(NSString *title){
[self setTitle:title forState:UIControlStateNormal];
return self;
};
}
- (UIButton *(^)(NSString *))selectedTitle {
return ^(NSString *title){
[self setTitle:title forState:UIControlStateNormal];
return self;
};
}
- (UIButton *(^)(NSString *))highlightTitle {
return ^(NSString *title){
[self setTitle:title forState:UIControlStateNormal];
return self;
};
}
- (UIButton *(^)(UIImage *))normalImage {
return ^(UIImage *image){
[self setImage:image forState:UIControlStateNormal];
return self;
};
}
- (UIButton *(^)(UIImage *))normalBackgroundImage {
return ^(UIImage *image){
[self setBackgroundImage:image forState:UIControlStateNormal];
return self;
};
}
- (UIButton *(^)(UIImage *))selectedImage {
return ^(UIImage *image){
[self setImage:image forState:UIControlStateSelected];
return self;
};
}
- (UIButton *(^)(UIImage *))selectedBackgroundImage {
return ^(UIImage *image){
[self setBackgroundImage:image forState:UIControlStateSelected];
return self;
};
}
- (UIButton *(^)(UIImage *))highlightedImage {
return ^(UIImage *image){
[self setImage:image forState:UIControlStateHighlighted];
return self;
};
}
- (UIButton *(^)(UIImage *))highlightedBackgroundImage {
return ^(UIImage *image){
[self setBackgroundImage:image forState:UIControlStateHighlighted];
return self;
};
}
@end
NS_ASSUME_NONNULL_END
这样就可以实现效果:
UIButton * btn = [UIButton button].normalTitle(@"Click").normalImage([UIImage imageNamed:@"button"]).selectedTitle(@"Clicked");
链式确实很优雅,不过Masonry
不止有链式的优雅,还有很多牛逼的想法,改天出一篇Masonry
源码的解析,膜拜一下大神。