The Util Designer
SwiftUI Localization的使用
xcode 13.4.1, swift 5.5, iOS 15.4
2022-08-19
有時我們需要為我們的App做Localization,這篇會講講如何簡單使用多語言化。
1. 先用List來顯示。
import SwiftUI

struct ContentView : View {
    var body: some View {
        List {
            Text("one")
            Text("two")
            Text("three")
            Text("four")
            Text("five")
            Text("six")
            Text("seven")
            Text("eight")
            Text("nine")
            Text("ten")
        }
    }
}
2. 使用多語言,需要創建Localizable.strings文檔,File->New->File...->Strings File :
3. 創建了的Localizable.strings文檔如下圖:
4. 在Project->Info->Localization,按+
5. 選擇Chinese, Traditional (zh-Hant)
6. 在確定框按Finish
7. 這樣就把Chinese, Traditional加到Localization上
8. 現在從Product Structure中的Localizable.strings就分有兩個子文檔,一個是English,另一個是Chinese, Traditional
9. 在Localizable (English),加入以下內容:
"one" = "ONE";
"two" = "TWO";
"three" = "THREE";
"four" = "FOUR";
"five" = "FIVE";
"six" = "SIX";
"seven" = "SEVEN";
"eight" = "EIGHT";
"nine" = "NINE";
"ten" = "TEN";
9. 在Localizable (Chinese, Traditional),加入以下內容:
"one" = "一";
"two" = "二";
"three" = "三";
"four" = "四";
"five" = "五";
"six" = "六";
"seven" = "七";
"eight" = "八";
"nine" = "九";
"ten" = "十";
10. 按Product->Scheme->Edit Scheme...
11. 在Run->Options->App Language選擇Chinese, Traditional
13. 然後重新運行App,就使用了Localizable (Chinese, Traditional)的字來顯示了。
14. 如果用ForEach,為了能拿到相應的多語言文字,需要使用LocalizedStringKey來拿到相應的多語言文字,實作如下:

import SwiftUI

struct ContentView : View {
    let numbers = ["one", "two", "three", "four", "five",
    "six", "seven", "eight", "nine", "ten"]
    var body: some View {
        List {
            ForEach(numbers, id:\.self) { number in
                Text(LocalizedStringKey(number))
            }
        }
    }
}