使用SwfitGen達成目標
只需在strings文件中添加對應本地化key=value箱舞,編譯項目后即可自動生成string擴展屬性患膛,使用時可以使用點語法獲取本地化key。
依賴庫簡介
SwiftGen
SwiftGen是一個強大的開源工具蚁署,它允許開發(fā)者利用 Swift 的強類型和模式匹配能力自動化生成常量恶座、枚舉搀暑、結(jié)構(gòu)體等靜態(tài)類,極大地提高了開發(fā)效率和代碼可維護性跨琳。通過解析資源文件(如本地化字符串自点、顏色、字體湾宙、圖像等)和 storyboard 文件樟氢,SwiftGen 可以幫助我們避免手動輸入這些重復代碼,從而專注于更有價值的工作侠鳄。
Stencil
Stencil 是一款靈感來源于Django和Mustache的輕量級模板引擎埠啃,專為Swift開發(fā)者設計∥岸瘢可用于Markdown渲染碴开、Swift代碼生成、自動化工具等博秫,==SwiftGen依賴Stencil生成代碼==潦牛。
集成步驟
1. pod集成SwiftGen或使用Homebrew安裝
pod 'SwiftGen'
# 通過 Homebrew 安裝
brew install swiftgen
2. 初始化yml文件
yml文件是SwiftGen必須的配置文件,用于配置必要文件路徑挡育、參數(shù)等巴碗。
文件創(chuàng)建方式
- 命令行生成
swfitgen init
手動創(chuàng)建文件改后綴名為.yml
項目中用到的配置示例如下:
## 注:路徑是基于yml文件路徑配置
strings:
inputs:
- ../Resources/zh-Hant.lproj ##本地化strings文件路徑
outputs:
- templatePath: StringExtension.stencil ##stencil模板路徑
output: LocalizedString.swift ##Swift代碼文件輸出路徑
3. 創(chuàng)建stencil模板文件
- 創(chuàng)建方式
手動創(chuàng)建文件改后綴名為.stencil - 項目中用到的模板示例如下:
import Foundation
import Localize_Swift
extension String {
{% for table in tables %}
{% for d in table.levels.strings %}
/// {{ d.translation }}
static let {{ d.key }} = "{{ d.name }}".localized()
{% endfor %}
{% endfor %}
}
模板示例簡單說明:
tables為strings文件內(nèi)容,數(shù)組格式即寒,遍歷數(shù)組元素橡淆,獲取到其中的鍵值對召噩,使用點語法可根據(jù)key讀取到對應的value值,依次獲取到所需要的內(nèi)容逸爵,生成對應代碼具滴,次格式為通用固定格式。想要知道tables中都包含什么內(nèi)容师倔,可以使用{{ tables }}查看构韵。
4. 配置shell腳本
在主工程TARGETS->Build Phases中新增New Run Script Phases, 添加如下腳本:
if [[ -f "${PODS_ROOT}/SwiftGen/bin/swiftgen" ]]; then
${PODS_ROOT}/SwiftGen/bin/swiftgen config run --config ${SRCROOT}/項目名/LocalizableConfig/swiftgen.yml
else
echo "warning: SwiftGen is not installed. Run 'pod install --repo-update' to install it."
fi
shell腳本簡單說明:
"
{SRCROOT}/項目名/LocalizableConfig/swiftgen.yml為yml配置文件路徑
5. 組件中使用SwiftGen
流程同上,唯一需要的是shell腳本的配置趋艘,需要再podspec中添加對應腳本配置疲恢,配置如下:
#script_phase
script = <<-CMD
if [[ -f "${PODS_ROOT}/SwiftGen/bin/swiftgen" ]]; then
${PODS_ROOT}/SwiftGen/bin/swiftgen config run --config ${PODS_ROOT}/../../TO_Modules/組件名/組件名/Classes/LocalizableConfig/swiftgen.yml
else
echo "warning: SwiftGen is not installed. Run 'pod install --repo-update' to install it."
fi
CMD
#shell_path指定腳本運行環(huán)境,execution_position指定編譯前還是編譯后執(zhí)行
s.script_phase = { :name => 'swiftgen script', :script => script, :shell_path =>'/bin/sh', :execution_position => :before_compile }
s.dependency 'SwiftGen'
配置簡單說明:
注意swiftgen路徑及yml配置文件路徑是否正確
6. 后期規(guī)劃
需整理出一個csv或Excel文件,用于統(tǒng)一管理key對應的各個國家語言翻譯致稀,使用腳本自動生成strings文件冈闭,再配合SwiftGen,將極大減少工作量抖单。