SwiftUI 本地化带参数的文本

发布
更新
字数 245
阅读 2 分钟
阅读量 561

参考 Text 本地化文档 https://developer.apple.com/documentation/swiftui/text#Localizing-strings。如果使用 string 变量,需要转化为 LocalizedStringKey , 例如自定义 View,需要传递一个文本参数,可以设置为

// Your view code block
var message: LocalizedStringKey
// ...

带参数文本

准备 Localizable.strings

"%@ time" = "%@次"

使用

var indexFormatter: NumberFormatter {
    let formatter = NumberFormatter()
    formatter.locale = .current
    formatter.numberStyle = .ordinal
    return formatter
}

let index = 3
// 需要先把 index 格式化为文本
Text("\(index as NSNumber, formatter: indexFormatter) time")

// 3rd time
// 第三次

注意模版中使用了 %@ 所以需要需先对 index 进行格式化

参考 https://developer.apple.com/documentation/swiftui/preparing-views-for-localization

String 本地化

string 本地化

String(localized: "time")

string 变量本地化

Text,不能直接本地化 string 变量。如果要格式化的 string 是变量或包含变量的表达式,需要使用 String.LocalizationValue

var timesUnit = "time"
String(localized: .init(stringLiteral: timesUnit))

String(localized: .init(stringLiteral: "next_time_notification_\((0..<5).randomElement() ?? 0)"))

带参数文本

String.localizedStringWithFormat(
    // 先对模版本地化处理
	String(localized: "%@ time"),
    // 替换参数
    Formatter.indexFormatter.string(from: index as NSNumber)!
)