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

相關文章
相關標籤/搜索