iOS链式编程

在iOS中,链式编程虽然用的不太多,但是,在特定的应用环境下,利用block实现链式编程的话,会大大的提高编程效率,并且代码直观易读。
初次接触链式编程是在Masonry中,不得不承认那种写法看起来十分直观,调用起来也很简单。
下边我会用一个例子来对比一下日常编程方式和链式编程。

/**
 * 日常编程方式
 */
#import 

@interface CustomView : UIView

// 设置View的大小及位置
- (void)setViewFrame:(CGRect)frame;

// 设置View的颜色
- (void)setViewColor:(UIColor *)color;

@end

实现:

- (void)setViewFrame:(CGRect)frame {
    self.frame = frame;
}

- (void)setViewColor:(UIColor *)color {
    self.backgroundColor = color;
}

调用:

- (void)viewOption {
    CustomView *customView = [[CustomView alloc] init];
    [customView setViewFrame:CGRectMake(165, 300, 100, 100)];
    [customView setViewColor:[UIColor cyanColor]];
    [self.view addSubview:customView];
}

实现效果:

实现效果

下面,我们使用链式编程实现

#import 

@interface CustomView : UIView

/**
 *  设置View的大小及位置
 */
- (CustomView *(^)(CGRect))viewFrame;

/**
 *  设置View的颜色
 */
- (CustomView *(^)(UIColor *))ViewColor;

/**
 *  仿造Masonry
 *
 *  @param block 对View的处理
 *
 *  @return UIView
 */
+ (UIView *) makeCustomView:(void (^)(CustomView *))block;

@end

实现:

- (CustomView *(^)(CGRect))viewFrame {
    return ^CustomView *(CGRect frame) {
        self.frame = frame;
        return self;
    };
    
}

- (CustomView *(^)(UIColor *))ViewColor {
    return ^CustomView *(UIColor *color) {
        self.backgroundColor = color;
        return self;
    };
}

+ (UIView *)makeCustomView:(void (^)(CustomView *))block {
    CustomView *view = [[CustomView alloc] init];
    block(view);
    return view;
}

调用:

- (void)viewOption {
    UIView *customView = [CustomView makeCustomView:^(CustomView *custom) {
        custom.viewFrame(CGRectMake(165, 300, 100, 100)).ViewColor([UIColor cyanColor]);
    }];
    [self.view addSubview:customView];
}

最后结果和日常书写方式实现相同,但是在调用上更加清晰直观。
ben li

你可能感兴趣的:(iOS链式编程)