首页 > 代码库 > 第四十一篇、Masonry利用Block实现链式编程

第四十一篇、Masonry利用Block实现链式编程

一直都觉得使用Masonry的时候语法特别优雅,很早的时候就想尝试下怎么实现,

一直都没弄明白,直到最近看见一篇叫block实现链式编程的

使用实例:

 UIButton * btn = [UIButton button].normalTitle(@"普通状态").normalImage([UIImage imageNamed:@"icon_help"]).selectedTitle(@"选中状态");

 

/// 声明文件@interface UIButton (JQExtension)/// 连接符,没啥实际意义,蛋疼的时候可以无限.set....- (instancetype)set; + (instancetype)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   实现文件#import "UIButton+GKExtension.h" @implementation UIButton (GKExtension)- (instancetype)set {    return self;} + (instancetype)button {    return [self buttonWithType:UIButtonTypeCustom];} - (UIButton *(^)(NSString *))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;    };}

 

第四十一篇、Masonry利用Block实现链式编程