我们一般会写很多的分类,这样会极大的方便的我们的代码。
比如我们需要给创建的一个UILabel对象赋值一些属性,常规的写法一般如下:
_priceLb.font = kFontPingFangRegularSize(10.f);
_priceLb.textColor = kColor_666666;
但是我们如果使用链式语法实现其功能,并用分类添加新的属性,重写其get方法,我们的代码可以是这样的:
weakSelf.hsSearchLb.aFont(kFontPingFangBoldSize(16)).
aTextColor([UIColor blackColor]);
_hsSearchLb.aFont(kFontPingFangBoldSize(16)).
aTextColor([UIColor blackColor]).
aAlignment(NSTextAlignmentCenter).
aText(@"花生搜索");
具体实现代码
#import <UIKit/UIKit.h>
typedef UILabel *(^LeeFontBlock)(UIFont *aFontSize);
typedef UILabel *(^LeeTextBlock)(NSString *aText);
typedef UILabel *(^LeeTextColorBlock)(UIColor *aColor);
typedef UILabel *(^LeeNumberOfLinesBlock)(NSInteger aNumber);
typedef UILabel *(^LeeTextAlignmentBlock)(NSTextAlignment aAlignment);
@interface UILabel (LeeChainBlock)
@property (nonatomic,copy,readonly) LeeFontBlock aFont;
@property (nonatomic,copy,readonly) LeeTextColorBlock aTextColor;
@property (nonatomic,copy,readonly) LeeTextBlock aText;
@property (nonatomic,copy,readonly) LeeNumberOfLinesBlock aNumberOfLines;
@property (nonatomic,copy,readonly) LeeTextAlignmentBlock aAlignment;
@end
#import "UILabel+LeeChainBlock.h"
@implementation UILabel (LeeChainBlock)
- (LeeTextBlock)aText{
__weak typeof(self) weakSelf = self;
return ^(NSString *aTextStr){
__strong typeof(weakSelf) strongSelf = weakSelf;
strongSelf.text = aTextStr;
return strongSelf;
};
}
- (LeeNumberOfLinesBlock)aNumberOfLines{
__weak typeof(self) weakSelf = self;
return ^(NSInteger aNumber){
__strong typeof(weakSelf) strongSelf = weakSelf;
strongSelf.numberOfLines = aNumber;
return strongSelf;
};
}
- (LeeFontBlock)aFont{
__weak typeof(self) weakSelf = self;
return ^(UIFont *aFont){
__strong typeof(weakSelf) strongSelf = weakSelf;
strongSelf.font = aFont;
return strongSelf;
};
}
- (LeeTextColorBlock)aTextColor{
__weak typeof(self) weakSelf = self;
return ^(UIColor *aColor){
__strong typeof(weakSelf) strongSelf = weakSelf;
strongSelf.textColor = aColor;
return strongSelf;
};
}
- (LeeTextAlignmentBlock)aAlignment{
__weak typeof(self) weakSelf = self;
return ^(NSTextAlignment aAlignment){
__strong typeof(weakSelf) strongSelf = weakSelf;
strongSelf.textAlignment = aAlignment;
return strongSelf;
};
}
@end
如下是链式语法相关博客
第一篇:链式语法实现分析
第二篇:链式语法使用实战
网友评论