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文件右邊填寫(xiě)各個(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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容