【问题标题】:How can I use different array based on the device language?如何根据设备语言使用不同的数组?
【发布时间】:2026-02-11 00:10:02
【问题描述】:

在我的应用程序中,我有 3 个数组,一个用于基本语言(英语),另外两个用于本地化。我可以根据用户设备上设置的语言选择特定的数组吗?例如,如果设备设置为使用德语,我想将短语翻译成德语。

这是我创建的变量

var enQuotes:[String] = []
var itQuotes:[String] = []
var deQuotes:[String] = []

这是从文件中获取引号的方法

enQuotes = quotes_en.getEnQuotes()
itQuotes = quotes_it.getItQuotes()
deQuotes = quotes_de.getDeQuotes()

这是我用来设置随机短语的代码

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let firstTouch = touches.first {
        let hitView = self.view.hitTest(firstTouch.location(in: self.view), with: event)

        if hitView === backgroundView {

            let randomArray = Int(arc4random_uniform(UInt32(enQuotes.count)))
            phraseLbl.text = (enQuotes[randomArray])

            print("touch is inside")

        } else {
            print("touch is outside")
        }
    }
}

【问题讨论】:

  • 如何使用LocalizedString()。您为每个引号设置键/值,然后构造一个数组?

标签: ios arrays iphone swift translate


【解决方案1】:

将引号作为本地化的属性列表资源“Quotes.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">
<array>
    <string>First Quote</string>
    <string>Second Quote</string>
    <string>Third Quote</string>
</array>
</plist>

为每种支持的语言添加本地化。

在运行时,使用Bundle.url(forResource:withExtension:) 方法定位属性列表,这将自动选择 根据用户的语言设置选择正确的版本。 然后读取数据并将其反序列化为字符串数组:

let url = Bundle.main.url(forResource: "Quotes", withExtension: "plist")!
let data = try! Data(contentsOf: url)
let quotes = try! PropertyListDecoder().decode([String].self, from: data)

(强制展开和强制尝试在这里是可以接受的,因为任何 失败将表示需要修复的编程错误。)

【讨论】:

    最近更新 更多