Objective-C 之 链式建立UI

1、建立方法的比较

1. 常规方法
UILabel* label = [UILabel new];
[self.view addSubview:label];
label.backgroundColor = UIColor.redColor;
label.text = @"String...";
label.textColor = UIColor.orangeColor;
label.textAlignment = NSTextAlignmentCenter;
复制代码
2. 链式方法
[UILabel xj_make:^(XJLabelMaker *make) {
    make.addTo(self.view)
        .backgroundColor(UIColor.redColor)
        .text(@"String...")
        .textColor(UIColor.orangeColor)
        .textAlignment(NSTextAlignmentCenter);
}];
复制代码

2、原理

每一个属性设置后都会返回对象自己,所以能够一直使用.来设置属性。git

3、实现

1. 定义UIView的属性
@property (nonatomic, copy, readonly) XJViewMaker* (^frame)(CGRect frame);
复制代码
2. 实现属性方法

给UIView赋值后返回selfgithub

- (XJViewMaker* _Nonnull (^)(CGRect))frame {
    return ^XJViewMaker* (CGRect frame) {
        self.view1.frame = frame;
        return self;
    };
}
复制代码
3. 给UIView添加一个类别,定义一个类方法,并实现:

定义bash

@interface UIView (XJMaker)
+ (instancetype)xj_make:(void(^)(XJViewMaker* make))make;
@end
复制代码

实现ui

@implementation UIView (XJMaker)

+ (instancetype)xj_make:(void (^)(XJViewMaker* ))make {
    
    XJViewMaker* maker = [[XJViewMaker alloc] initView];
    if (make) {
        make(maker);
    }
    
    return maker.view1;
}

@end
复制代码

4、使用说明

1. 项目地址

github.com/MrLfm/Creat…atom

2. 使用方法

下载项目后,把XJViewMaker文件夹拖到你的工程中,导入头文件便可使用:spa

#import "XJViewMakerHeader.h"
复制代码
3. 说明

若是缺乏属性,可参照其余属性自行添加。code

本文参考了如下文章,感谢做者提供的思路:对象

www.jianshu.com/p/513379a67…get

www.jianshu.com/p/602348527…string

相关文章
相关标签/搜索