iOS 链式编程

2019-04-16  本文已影响0人  nickNameDC

链式编程


链式编程简单的说就是将多个方法用点语法连接起来,让代码更加简洁,可读性更强。例如MasonrySDAutoLayout;

make.left.right.mas_equalTo(0);

这一行代码,就同时实现了设置左右两边间距都为0;

Masonry怎么实现链式调用的


- (MASConstraintMaker *)left;
- (MASConstraint * (^)(CGFloat offset))offset;
- (MASConstraintMaker *)with;

创建我们自己的链式调用


我觉的我们可以通过链式调用来设置view的一些属性,例如Label,首先我们要想象一下我们最终实现好调用的样子,

   [UILabel dcMaker_creat].frame(CGRectMake(100, 200, 100, 50))
    .text(@"this is a label")
    .textColor([UIColor redColor])
    .font(15).fontWeight(UIFontWeightMedium)
    .textAlignment(NSTextAlignmentLeft)
    .numberOfLines(2)
    .intoView(self.view);

这种方式更像SDAutoLayout,我个人更喜欢这种风格,因为我觉得没必要像Masonry那样通过mas_makeConstraints:^(MASConstraintMaker *make) {}];MASConstraintMaker抛出来,然后在block中设置属性。我觉的可以通过某个方法拿到一个maker,然后就可以不停的点语法设置属性,个人觉得这样用起来非常爽哈哈哈;

@property (nonatomic,copy,readonly) DCLabelMaker* (^font)(CGFloat font);

这样外面用的时候就是maker.font(15),这样,因为返回的是DCLabelMaker,所以还能接着调用点语法;这样就实现了连续通过点语法调用。

-(DCLabelMaker * _Nonnull (^)(CGFloat))font{
    __weak typeof(self) weak_self = self;
    return ^DCLabelMaker* (CGFloat font){
        weak_self.viewAttribute.font = font;
        return weak_self;
    };
}

.h文件添加属性

@property (nonatomic,copy,readonly) UILabel* (^intoView)(UIView *superView);

.m文件实现方法

- (UILabel * _Nonnull (^)(UIView * _Nonnull))intoView{
    __weak typeof(self) weak_self = self;
    return ^UILabel * _Nonnull(UIView * _Nonnull superView) {
        DCViewAttribute *viewAttribute = weak_self.viewAttribute;
        UILabel *label = [[UILabel alloc]initWithFrame:viewAttribute.frame];
        label.font = [UIFont systemFontOfSize:viewAttribute.font];
        [superView addSubview:label];
        return label;
    };
}
.h
+ (DCLabelMaker *)dcMaker_creat;

.m
+(DCLabelMaker *)dcMaker_creat{
    DCLabelMaker *maker = DCLabelMaker.new;
    maker.viewAttribute = DCViewAttribute.new;
    return maker;
}

大功告成!!!

这样外部调用的时候就如我们上面所想的样子了

   [UILabel dcMaker_creat].frame(CGRectMake(100, 200, 100, 50))
    .text(@"this is a label")
    .textColor([UIColor redColor])
    .font(15).fontWeight(UIFontWeightMedium)
    .textAlignment(NSTextAlignmentLeft)
    .numberOfLines(2)
    .intoView(self.view);

参考链接:https://blog.csdn.net/cAj3Z1hurtGNR2/article/details/78103850
代码链接:https://github.com/daichuan/DCViewMaker/tree/master

上一篇下一篇

猜你喜欢

热点阅读