iOS 开发每天分享优质文章iOS - Developer - OC 进阶大全iOS 功能类

Objective-C 之 链式创建UI

2019-07-11  本文已影响104人  我唔知啊

一、创建方法的比较

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);
}];

二、原理

每个属性设置后都会返回对象本身,因此可以一直使用.来设置属性。

三、实现

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

给UIView赋值后返回self

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

定义

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

实现

@implementation UIView (XJMaker)

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

@end

四、使用说明

1. 项目地址

https://github.com/MrLfm/CreateUILikeChain

2. 使用方法

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

#import "XJViewMakerHeader.h"
3. 说明

如果缺少属性,可参照其他属性自行添加。

本文参考了以下文章,感谢作者提供的思路:

https://www.jianshu.com/p/513379a67130

https://www.jianshu.com/p/60234852767d

上一篇下一篇

猜你喜欢

热点阅读