Python根據(jù)Json生成Objective-c代碼

代碼地址:https://github.com/LiPengYue/BuildiOSCode.git

目標(biāo):

1、 解析UI稿(HTML文件),根據(jù)HTML生成完整的Objective-c代碼(未完成)

  • 完成了xcode XIB 解析成json,json轉(zhuǎn)Objective-c代碼

2、 根據(jù)json生成ViewModel、model、View文件,(完成)

3、 根據(jù)json自動(dòng)給模板添加 子視圖、視圖布局、視圖屬性賦值的代碼(完成)

Json 數(shù)據(jù)源獲取:

一、 UI稿轉(zhuǎn)json(未完成)

終極目標(biāo)是把藍(lán)湖HTML文件轉(zhuǎn)成一個(gè)個(gè)可解析的json,然后轉(zhuǎn)成Objective-c代碼,但是前端代碼不是很熟悉,所以先用xcode的xib進(jìn)行了json轉(zhuǎn)化

二、 Xcode XIB 轉(zhuǎn)json

XIB 可視化編輯屬性

每個(gè)子UI視圖,生成代碼都需要有幾個(gè)要素:

1、視圖樣式相關(guān): border、borderColor,backgroundColor,text,image等

2、 網(wǎng)絡(luò)接口相關(guān):image, text, backgroundColor等

為了在XIB中展示這些接口,方便為json生成提供數(shù)據(jù),我在OC demo中添加了幾個(gè)分類(添加IBInspectable標(biāo)識(shí),表示可以在xib中展示)

// View
@interface UIView (PYBaseBuildCodeXIB)
@property (nonatomic, assign) IBInspectable   CGFloat  cornerRadius;//圓角
@property (nonatomic, strong) IBInspectable   UIColor *borderColor;//邊框顏色
@property (nonatomic, assign) IBInspectable   CGFloat  borderWidth;//邊框?qū)挾?@property (nonatomic, copy) IBInspectable NSString *propertyName;
@property (nonatomic, copy) IBInspectable NSString *bgColorAPI;
@end
  
// label
@interface UILabel (PYBaseBuildCodeXIB)
@property (nonatomic, copy) IBInspectable NSString *textColorAPI;
@property (nonatomic, copy) IBInspectable NSString *textAPI;
@end

// image
@interface UIButton (PYBaseBuildCodeXIB)
@property (nonatomic, copy) IBInspectable NSString *textColorAPI;
@property (nonatomic, copy) IBInspectable NSString *textAPI;
@end

// image
@interface UIImageView (PYBaseBuildCodeXIB)
@property (nonatomic, copy) IBInspectable NSString *imageAPI;
@end
image.png

XIB 解析

HTML解析:XIB會(huì)生成一個(gè)HTML文件,解析HTML使用的是xml.dom.minidom三方庫(kù),

常量字符存儲(chǔ):HTML中特定的標(biāo)簽字段由iOSXIBDomParserStaticStr.py來(lái)存儲(chǔ)

解析model:

有基類iOSXIBDomParserButtonModel來(lái)處理View的一些基本屬性記錄,比如 borderColor、布局相關(guān)數(shù)據(jù)等

子類記錄特有的屬性值

image.png

使用

iOSXIBDomParser ,構(gòu)造函數(shù)傳入xib絕對(duì)路徑,調(diào)用viewModel.convertToDic函數(shù)來(lái)解析成字典

parser = iOSXIBDomParser(path)
contentDict = parser.viewModel.convertToDic()

Json 生成Objective-c代碼

代碼生成的思路步驟

image.png

1、 解析Json,獲取json中的屬性定義列表、賦值子視圖網(wǎng)絡(luò)數(shù)據(jù)列表、懶加載視圖屬性列表、布局?jǐn)?shù)據(jù)列表

時(shí)機(jī)開(kāi)發(fā)中,我們經(jīng)常使用宏定義來(lái)創(chuàng)建UIColor、UIFont,所以工具提供了colorConfig.txt、fontConfig.txt文件來(lái)配置創(chuàng)建規(guī)則

colorConfig.txt
 {
     "annotation_NetApiCreateColor": "根據(jù)字段創(chuàng)建UIColor對(duì)象,'#colorName#' 為字段名",
     "NetApiCreateColor":"[UIColor : colorWithName: #colorName#]",
     "annotation_DefineHexCreateColor": "根據(jù)宏定義創(chuàng)建UIColor對(duì)象,'#colorName#' 為16進(jìn)制參數(shù)",
     "DefineHexCreateColor":"ColorDefine(#colorName#)",
     "annotation_StaticCreateColorList": "默認(rèn)宏定義UIColor對(duì)象數(shù)組,key為宏定義,value為16進(jìn)制顏色",
     "DefineCreateColorList": [
         "define_red":"0xFFFF0000"
     ]
 }

fontConfig.txt
{
        "annotation_DefineCreateFont": "根據(jù)字體名創(chuàng)建UIFont對(duì)象,'#FontSize#' 會(huì)替換成float類型",
        "DefineCreateFont": {

            "PingFangSC-Regular": "FontPingFangSCR(#fontSize#)",
            "PingFangSC-Medium": "FontPingFangSCM(#fontSize#)",
            "PingFangSC-Light": "FontPingFangSCL(#fontSize#)",
        },
        "annotation_CreateFont": "根據(jù)family_name創(chuàng)建UIFont對(duì)象,'#familyName#' 為font名, #fontSize#為size",
        "CreateFont": "[UIFont fontWithName:#familyName# size:#fontSize#]",
}

2、 根據(jù)模板文件,把對(duì)應(yīng)的數(shù)據(jù)生成代碼,插入到模板代碼對(duì)應(yīng)的位置中

在模板代碼中,插入對(duì)應(yīng)的關(guān)鍵字,使用正則來(lái)匹配對(duì)應(yīng)的位置,具體代碼參見(jiàn):IOSTemplateRegulars.py

3、 格式化代碼格式:ios_code_style.py

4、 輸出view/viewModel文件

在輸出文件的時(shí)候,需要標(biāo)注文件頭信息以及存儲(chǔ)的位置,提供了rootConfig.text來(lái)進(jìn)行配置

{
         "template_userNameKey": "名稱",
         "template_nickNameKey": "昵稱",

         "baseViewModelName": "viewModel的父類",
         "dataSouceName": "view持有的ViewModel屬性名",

         "templateViewName": "模板View名",
         "templateBaseViewName": "模板view父類名",
         "templateViewLayoutPointerName":"模板view承載子視圖的view屬性名",

         "templateViewModelName": "模板ViewModel名",
         "templateBaseViewModelName": "模板ViewModel父類名",

         "templateViewPath": "模板view的路徑",
         "templateViewModelPath": "模板ViewModel路徑",

         "savePath": "生成的代碼存儲(chǔ)路徑"

     }

生成之后的頭文件目錄為

代碼生成工具的代碼結(jié)構(gòu)

使用:

步驟:

1、 創(chuàng)建一個(gè)Objective-c項(xiàng)目,把目錄中的PYBaseBuildCodeXIBiOSTemplate文件夾拖入項(xiàng)目中

2、 創(chuàng)建xib文件,并布局視圖、 xib文件右邊填寫各個(gè)子視圖的參數(shù):api、propertyName...

3、 找到ios_code_builder.py文件運(yùn)行man函數(shù)

4、 配置彈出的colorConfig.text、 fontConfig.text、rootConfig.text文件

5、 在控制臺(tái)回車,后完成代碼轉(zhuǎn)化

事例:


image.png

生成的cell.m文件

//
//  PYXIBViewCell
//  生成View
//  Created by 李鵬躍 on 2024/1/21.
//  Copyright ? 2024 lpy. All rights reserved.
//  


#import "PYXIBViewCell.h"

@interface PYXIBViewCell()

@property (nonatomic,strong) UILabel *titleLabel;
@property (nonatomic,strong) UILabel *subTitle;
@property (nonatomic,strong) UIImageView *coverImage;
@property (nonatomic,strong) UIButton *byButton;

@end

@implementation PYXIBViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setupViews];
    }
    return self;
}

- (void)didSetBaseViewModel:(iOSTemplateTableBaseViewModel *)baseViewModel {
    if (![baseViewModel isKindOfClass:PYXIBViewCellViewModel.class]) {
        return;
    }
    self.viewModel = (PYXIBViewCellViewModel *)baseViewModel;
}

- (void) setViewModel:(PYXIBViewCellViewModel *)viewModel {
    _viewModel = viewModel;
    
    // titleLabel
    self.titleLabel.text = self.viewModel.title;
    self.titleLabel.textColor = [UIColor py_colorWithHex: self.viewModel.titleColor ?: @"0xFAFAFA"];
                  
    // subTitle
    self.subTitle.text = self.viewModel.subTitle;
    self.subTitle.textColor = [UIColor py_colorWithHex: self.viewModel.subTitleColor ?: @"0xFAFAFA"];
                  
    // coverImage
    [self.coverImage sd_setImageWithURL:[NSURL URLWithString:self.viewModel.cover?:@""]];

}

- (void)setupViews {
    
    [self.contentView addSubview:self.titleLabel];
    [self.contentView addSubview:self.subTitle];
    [self.contentView addSubview:self.coverImage];
    [self.contentView addSubview:self.byButton];

    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(17));
        make.top.equalTo(self.coverImage.mas_top);
        make.left.equalTo(self.coverImage.mas_right).offset(8);
        make.right.lessThanOrEqualTo(@(-16));
    }];
    [self.subTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(14));
        make.top.equalTo(self.titleLabel.mas_bottom).offset(8);
        make.left.equalTo(self.titleLabel.mas_left);
    }];
    [self.coverImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(60));
        make.height.equalTo(@(60));
        make.top.equalTo(self.contentView.mas_top).offset(10);
        make.left.equalTo(self.contentView.mas_left).offset(16);
    }];
    [self.byButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(44));
        make.width.equalTo(@(44));
        make.right.equalTo(@(-16));
        make.bottom.equalTo(self.contentView);
    }];
}

// MARK: - getter && setter

- (UILabel *) titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.layer.borderColor = KColorRGB(0xFFFF00FF).CGColor;
        _titleLabel.layer.borderWidth = 1;
        _titleLabel.layer.cornerRadius = 2;
        _titleLabel.textColor = KColorRGB(0xFF222222);
        _titleLabel.font = KFontR(12);
        _titleLabel.textAlignment = NSTextAlignmentLeft;
        _titleLabel.text = @"titleLabel";
    }
    return _titleLabel;
}

- (UILabel *) subTitle {
    if (!_subTitle) {
        _subTitle = [[UILabel alloc]init];
        _subTitle.textColor = KColorRGB(0x8032ADE6);
        _subTitle.font = KFontR(10);
        _subTitle.textAlignment = NSTextAlignmentLeft;
        _subTitle.text = @"subTitle";
    }
    return _subTitle;
}

- (UIImageView *) coverImage {
    if (!_coverImage) {
        _coverImage = [[UIImageView alloc]init];
        _coverImage.layer.cornerRadius = 4;
    }
    return _coverImage;
}
- (UIButton *) byButton {
    if (!_byButton) {
        _byButton = [[UIButton alloc]init];
        _byButton.layer.borderColor = KColorRGB(0xFFEB0159).CGColor;
        _byButton.layer.borderWidth = 1;
        _byButton.layer.cornerRadius = 2;
        [_byButton setTitleColor:KColorRGB(0xFFEB0159) forState:UIControlStateNormal];
        _byButton.titleLabel.font = KFontR(12);
        [self.byButton setTitle:@"購(gòu)買" forState: UIControlStateNormal];
        [_byButton addTarget:self action:@selector(click_byButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _byButton;
}
- (void)click_byButton {
        
}

// MARK: - containerHeight
+ (CGFloat)getContainerViewHeightWithViewModel:(iOSTemplateTableBaseViewModel *)viewModel {
    if (![viewModel isKindOfClass:PYXIBViewCellViewModel.class]) {
        return CGFLOAT_MIN;
    }
    PYXIBViewCellViewModel *vm = (PYXIBViewCellViewModel *)viewModel;
    CGFloat h = CGFLOAT_MIN;
    return h;
}


@end

viewModel.h文件

//
//  PYXIBViewCellViewModel
//  生成View
//  Created by 李鵬躍 on 2024/1/21.
//  Copyright ? 2024 lpy. All rights reserved.
//  


#import "iOSTemplateBaseViewModel.h"

NS_ASSUME_NONNULL_BEGIN

@interface PYXIBViewCellViewModel : iOSTemplateBaseViewModel
@property (nonatomic,copy) NSString *titleColor;
@property (nonatomic,copy) NSString *title;
@property (nonatomic,copy) NSString *subTitleColor;
@property (nonatomic,copy) NSString *subTitle;
@property (nonatomic,copy) NSString *cover;

@end

NS_ASSUME_NONNULL_END

為了學(xué)習(xí)Python3.9,我構(gòu)思了這個(gè)Python生成Objective-c代碼項(xiàng)目,以項(xiàng)目來(lái)推動(dòng)學(xué)習(xí),讓學(xué)習(xí)更有動(dòng)力,學(xué)習(xí)成果更加扎實(shí)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,837評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,196評(píng)論 3 414
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事。” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 175,688評(píng)論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 62,654評(píng)論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,456評(píng)論 6 406
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 54,955評(píng)論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,044評(píng)論 3 440
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 42,195評(píng)論 0 287
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,725評(píng)論 1 333
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,608評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,802評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,318評(píng)論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,048評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 34,422評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 35,673評(píng)論 1 281
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,424評(píng)論 3 390
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,762評(píng)論 2 372

推薦閱讀更多精彩內(nèi)容