iOS高级开发程序员iOS从入门到放弃

iOS链式编程

2017-10-24  本文已影响28人  ptlCoder

谈到链式编程和函数式编程, Masonry就是最经典的代表, 没事可以多看看它的源码。
例如:
make.top.equalTo(self.myView).offset(10)

简单写一下链式编程的逻辑

//
//  UILabel+category.h
//  DEMO
//
//  Created by soliloquy on 2017/8/21.
//  Copyright © 2017年 soliloquy. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UILabel (category)

- (UILabel *)mas_makeCustomlabel:(void(^)(UILabel *label))block;
+ (UILabel *)mas_makeCustomlabel:(void(^)(UILabel *label))block;
- (UILabel *(^)(NSString *str))textStr;
- (UILabel *(^)(UIColor *tColor))tColor;
- (UILabel *(^)(NSInteger tFont))tFont;
- (UILabel *(^)(CGRect tFrame))tFrame;
@end

//
//  UILabel+category.m
//  DEMO
//
//  Created by soliloquy on 2017/8/21.
//  Copyright © 2017年 soliloquy. All rights reserved.
//

#import "UILabel+category.h"

@implementation UILabel (category)

- (UILabel *)mas_makeCustomlabel:(void(^)(UILabel *label))block {
    block(self);
    return self;
}

+ (UILabel *)mas_makeCustomlabel:(void(^)(UILabel *label))block {
    UILabel *l = [[UILabel alloc]init];
    block(l);
    return l;
}

- (UILabel *(^)(NSString *str))textStr {
    return ^(NSString *str) {
        self.text = str;
        return self;
    };
}

- (UILabel *(^)(UIColor *tColor))tColor {
    return ^(UIColor *c){
        self.textColor = c;
        return self;
    };
}

- (UILabel *(^)(NSInteger tFont))tFont {
    return ^(NSInteger f) {
        self.font = [UIFont systemFontOfSize:f];
        return self;
    };
}

- (UILabel *(^)(CGRect tFrame))tFrame {
    return ^(CGRect tFrame) {
        self.frame = tFrame;
        return self;
    };
}

@end

//
//  ViewController.m
//  DEMO
//
//  Created by soliloquy on 2017/8/21.
//  Copyright © 2017年 soliloquy. All rights reserved.
//

#import "ViewController.h"
#import "UILabel+category.h"


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel *l = [UILabel mas_makeCustomlabel:^(UILabel *label) {
        label.tFrame(CGRectMake(10, 100, 300, 100)).tFont(20).tColor([UIColor redColor]).textStr(@"服都是公开活动寺管会我偶的厚厚的回拨后回归hi奥");
    }];
    [self.view addSubview:l];
}

@end

Github: https://github.com/soliloquy-local/Method-chaining.git
以上就是简单的链式编程和函数式编程的入门思想,更多的还是要通过自己多阅读别人的代码,多去敲。总有一天你会很好的掌握这个思想,成为大神!!!

上一篇下一篇

猜你喜欢

热点阅读