You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为MVVM模式的Xcode自定义文件模板添加复选框

给Xcode MVVM模板添加复选框功能

嘿,恭喜你已经搞定了MVVM模板的基础配置!要给自定义Xcode模板加上复选框选项,核心是通过在你的plist配置里添加Template Options数组来实现的,我给你一步步说清楚:

1. 理解Xcode模板选项的配置逻辑

Xcode允许我们在模板的Info.plist中定义交互式选项,复选框是其中一种类型。你需要在主字典里添加Options键,对应一个数组,每个数组元素就是一个复选框的配置项。

2. 给你的plist添加复选框配置

结合你现有的plist内容,这里是添加了两个复选框的完整示例:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Kind</key>
    <string>Xcode.IDEFoundation.TextSubstitutionFileTemplateKind</string>
    <!-- 新增的复选框选项配置 -->
    <key>Options</key>
    <array>
        <dict>
            <!-- 唯一标识符,后面模板代码里要用到 -->
            <key>Identifier</key>
            <string>IncludeRepository</string>
            <!-- 复选框在Xcode界面显示的文字 -->
            <key>Name</key>
            <string>Generate Repository Layer</string>
            <!-- 选项类型,固定为Checkbox -->
            <key>Type</key>
            <string>Checkbox</string>
            <!-- 默认是否勾选,true为勾选,false为不勾选 -->
            <key>DefaultValue</key>
            <true/>
        </dict>
        <!-- 可以添加多个复选框,重复字典结构即可 -->
        <dict>
            <key>Identifier</key>
            <string>IncludeViewModelTests</string>
            <key>Name</key>
            <string>Generate ViewModel Test Files</string>
            <key>Type</key>
            <string>Checkbox</string>
            <key>DefaultValue</key>
            <false/>
        </dict>
    </array>
</dict>
</plist>

3. 在模板代码中使用复选框的状态

配置好plist后,你需要在模板的.swift文件(或其他模板文件)里通过条件编译判断复选框状态,决定是否生成对应代码块。

比如在你的ViewModel模板文件里,可以这样写:

import Foundation

class ___VARIABLE_productName:identifier___ViewModel {
    // 基础ViewModel核心代码
    
    #if ___OPTION_IncludeRepository___
    // 仅当勾选IncludeRepository时生成这部分代码
    private let repository: ___VARIABLE_productName:identifier___Repository
    
    init(repository: ___VARIABLE_productName:identifier___Repository = .init()) {
        self.repository = repository
    }
    #endif
}

#if ___OPTION_IncludeRepository___
// 勾选后自动生成Repository类
class ___VARIABLE_productName:identifier___Repository {
    // Repository层业务代码
}
#endif

4. 生效注意事项

  • 修改完plist和模板文件后,必须重启Xcode才能看到新的复选框选项
  • 确保你的模板文件放在正确路径(通常是~/Library/Developer/Xcode/Templates/Custom Templates/)

这样你就能在创建文件时,通过勾选复选框灵活控制是否生成特定层的代码啦!

内容的提问来源于stack exchange,提问作者Ranxan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:51:12