彼得潘的 Swift iOS / Flutter App 開發教室

學習 Swift iOS / Flutter App 開發的學生作品集

Follow publication

【iOS】#31 多語系設定 Localization

設定多國語系,讓 App 根據不同語言顯示不同文本

為了讓 App 根據使用者手機語言設定,顯示不同樣的文本,我們需要對 iOS App 進行 Localization (本地化),以下將介紹三個部分的多語系處理:

  • Storyboard 中的文本
  • 程式碼中的文本
  • App 顯示名稱

新增多國語言設定

不管是想要在 Storyboard 或者 Code 中進行多語系設定,都先要在 Info 中設定。在 Project 的 Info 中,可以找到 Localizations 設定。按下 「+」新增其他想要設定的語言

然後將 storyboard 的部分都打勾

Storyboard 中的文本

點選 storyboard 檔案後,到右邊欄位的 Localization 將欲設定的語系都打勾

打勾後左手邊的 storyboard 會變成可下拉的選單,其中 .strings 即為文本設定的檔案

打開後大致上會長成下方這樣。如果不清楚是哪一個元件的話,可以利用它提供的 ObjectID 去找元件

Storyboard 元件的 ObjectID 可以點選左邊欄位的第四個 Icon 查看

程式碼中的文本

Storyboard 適合設定靜態的文本,若是本身就直接用程式碼寫的,或者需要動態修改的文本,勢必需要從程式中設定 Localization

先新增一個 Strings File,並且命名為 Localizable

點選 Localizable.strings 檔案,一樣在右手邊的欄位將 Localization 打開

打開後此時 Localizable.strings 一樣會變成可下拉,其中的檔案就是本地化語言的設定檔

設定的方式如上圖所示,為 Key Value Pair,並且結尾用「;」,要記得不同檔案的 Key 名稱不要打錯。上方 %d 的部分是要帶入參數顯示,亦可以使用 %f 來寫是浮點格式

let noRecordStr = NSLocalizedString("GameVC.noRecord", comment: "")recordLabel.text = noRecordStr

在程式中使用時,利用 NSLocalizedString,第一個參數為 LocalizKey ,第二個參數是用來附註,讓開發人員更好了解這個 Key 代表什麼用途

// "GameVC.bestRecord" = "最佳紀錄:%ds"let bestRecordStr = NSLocalizedString("GameVC.bestRecord", comment: "")
let record = 100
recordLabel.text = String.localizedStringWithFormat(bestRecordStr, record)

若要帶入參數,需使用 String.localizedStringWithFormat,第二個參數帶入數值,將會顯示在 %d 的部分,達到動態改變文本的目的

App 顯示名稱

新增命名為 InfoPlist 的 Strings File,並且跟上述步驟相同,打開 Localization 設定

在檔案中輸入以下程式碼,Value 的部分設定成欲顯示的 App 名稱。請記得 Key 一定要是 CFBundleDisplayName 才會設定成功

"CFBundleDisplayName" = "App Name";

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

彼得潘的 Swift iOS / Flutter App 開發教室
彼得潘的 Swift iOS / Flutter App 開發教室
Leo Kuo
Leo Kuo

Written by Leo Kuo

Indie Game Developer | Frontend Developer | iOS Developer | UIUX

No responses yet

Write a response