###### tags: `第14屆IT邦鐵人賽文章` # 【在 iOS 開發路上的大小事2-Day02】多國語系的其他用法 在去年的時候,已經有介紹過多國語系的基本用法了 還沒看過的話,可以先去看一下~ [【在 iOS 開發路上的大小事-Day08】讓你的 App 與世界接軌!](https://ithelp.ithome.com.tw/articles/10259417) 而今天這篇則是要介紹當你的文字中有特定文字是非固定的 會根據不同的選擇顯示不同的值 以往會更動的值如果在多國文字的最前方或是最後方 那我們可以用下面這種寫法來設定 ```swift var test: Int = 10 // 更動的值在最前方 label.text = "\(test)\(NSLocalizedString("Test", comment: ""))" // 更動的值在最後方 label.text = "\(NSLocalizedString("Test", comment: ""))\(test)" ``` 那如果會變動的值是在多國文字的中間呢,像是下面這樣 ``` 測試123一二三 測試456一二三 測試789一二三 ``` 這種雖然可以透過設定兩個多國文字,再將其串接在一起,像是下面這樣 ```swift var test1: Int = 123 label.text = "\(NSLocalizedString("Test", comment: ""))\(test1)\(NSLocalizedString("One Two Three", comment: ""))" ``` 但是這樣在可讀性上可能不太好,那有沒有其他好的寫法呢,其實是有的 我們可以透過下面的這種寫法來達成 Swift API ↓  Objective-C API ↓  這邊由於我只會寫 Swift,所以我就只示範 Swift 的寫法 Objective-C 的寫法,可以參考 Apple Developer Documentation 裡面的寫法 首先,先打開 Localizable.strings 檔案,找到你要改的多國文字 以上面的為例,Key-Value 就會像下面的一樣 ```swift "Test" = "測試"; "One Two Three" = "一二三"; ``` 然後改用上面講到的 **localizedStringWithFormat(__:_:)** 這個方法 我們只需要將兩個多國文字改成一個 Key-Value,像是下面這樣 ```swift "Test One Two Three" = "測試%d一二三"; ``` 套用到 Label 上的話,就像下面這樣 ```swift var test12: Int = 123 label.text = String.localizedStringWithFormat(NSLocalizedString("Test", comment: ""), test12) ``` ### 參考資料 > 1. https://developer.apple.com/documentation/swift/string/1414192-localizedstringwithformat > 2. https://developer.apple.com/documentation/foundation/nsstring/1497301-localizedstringwithformat
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.