OC 链式编程

OC 链式编程_第1张图片
赏心悦目
  • _ config.h _
@interface Config : NSObject
  
   +(instancetype)defaultConfig;

   @property (nonatomic, strong) UIColor  *vBGColor; //小驼峰命名规范
   @property (nonatomic, assign) CGFloat  width;

     /**背景颜色*/
   @property (nonatomic, copy, readonly) Config *(^vBackGroundColor)(UIColor *color);
      /**宽度*/
   @property (nonatomic, copy, readonly) Config *(^vWidth)(CGFloat width);

@end
@implementation Config
 
 +(instancetype)defaultConfig{
      Config *config = [[Config alloc] init];
      config.vBGColor = [UIColor clearColor];
      config.width = 30.0f;
      return config;
  }

  -(Config *(^)(UIColor *)) vBackGroundColor{
      return ^(UIColor *color){
        self.vBGColor = color;
        return self;
      }
    }

  -(Config *(^)(UIColor *)) vWidth{
      return ^(CGFloat width){
        self.width = width;
        return self;
      }
   }

@end
  • View
@interface MMSegmentBar : UIView

/**
 快速创建一个控件

 @param frame frame
 @return view
 */
+ (instancetype)viewWithFrame: (CGRect)frame;

- (void)updateWithConfig:(void(^)(Config *config))configBlock;

@end
@interface View ()

@property (nonatomic, strong) Config *config;

@end

@implementation MMSegmentBar

+(instancetype)viewWithFrame:(CGRect)frame{
    View *view = [[View alloc] initWithFrame:frame];
    return view;
}

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = self.config.vBGColor;
    }
    return self;
}

-(void)updateWithConfig:(void (^)(Config *))configBlock{
    if (configBlock) {
        configBlock(self.config);
    }

    // 按照当前的self.config 进行刷新
    self.backgroundColor = self.config.vBGColor;


    [self setNeedsLayout];
    [self layoutIfNeeded];
}

#pragma mark - layout
- (void)layoutSubviews{
    [super layoutSubviews];

    // 更新布局

}
#pragma mark -- lazy
- (Config *)config{
    if (!_config) {
        _config = [Config defaultConfig];
    }
    return _config;
}

  • Example
 View * view = [View viewWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
 [view updateWithConfig:^(Config *config) {
        config.vBackGroundColor([UIColor whiteColor]).vWidth(20.0f);
  }];

既然已经决定,就勇敢的去吧。

决定吧

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