Localization in SwiftUI code is as easy as writing a String. To learn how to setup Localisable files, other basics about Localization follow along (UIKit related code can be ignored):
SwiftUI代码中的本地化就像编写String一样容易。 要了解如何设置可本地化的文件,请遵循其他有关本地化的基础知识(可以忽略与UIKit相关的代码):
For SwiftUI Localization, We will be using the following Localisable setup:
对于SwiftUI本地化,我们将使用以下Localisable设置:
"Content" = "Если эта цель будет достигнута в эпоху Возрождения, свободы, ценность личности, которую принесла нам западная цивилизация, исчезнет в одночасье.";
"Quotes" = "Котировки";
"Author_Name %@" = "Имя автора: %@";
<?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">
<dict>
<key>%llu Like(s)</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@v1_likes@</string>
<key>v1_likes</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>llu</string>
<key>zero</key>
<string>%llu Like</string>
<key>one</key>
<string>%llu Like</string>
<key>other</key>
<string>%llu Likes</string>
</dict>
</dict>
</dict>
</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">
<dict>
<key>%llu Like(s)</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@v1_likes@</string>
<key>v1_likes</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>llu</string>
<key>few</key>
<string>%llu Лайка</string>
<key>many</key>
<string>%llu Лайков</string>
<key>one</key>
<string>%llu лайк</string>
<key>other</key>
<string>%llu Лайков</string>
<key>zero</key>
<string>%llu Нравится</string>
</dict>
</dict>
</dict>
</plist>
SwiftUI localisable works with String interpolation. SwiftUI Text has a default initialiser:
SwiftUI可本地化可用于String插值 。 SwiftUI Text具有默认的初始化程序:
public init(_ key: LocalizedStringKey, //localisation key
tableName: String? = nil, //table name if nil takes Localisable.strings and Localisable.stringsDict
bundle: Bundle? = nil, //default main bundle
comment: StaticString? = nil)
We can initialise Text directly with Localization key, like following:
我们可以使用Localization键直接初始化Text,如下所示:
Text("Quotes")//renders:
/*
English: Quotes
Russian: Котировки
*/---------------------------------------------------------------let author = "Jhon Doe"
Text("Author_Name \(self.author)")
//renders:
/*
English: Author Name: Jhon Doe
Russian: Имя автора: Jhon Doe
*/---------------------------------------------------------------let likes: UInt = 10
Text("\(self.likes) Like(s)")
//renders:
/*
English: 10 Likes
Russian: 10 Лайков
*/
Easy and clean!
简单干净!
import SwiftUI
struct ContentView: View {
private static let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .short
return formatter
}()
let likes: UInt = 10
let publishedAt = Date()
let author = "Jhon Doe"
var body: some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
Text("\(publishedAt, formatter: Self.formatter)")
.foregroundColor(.secondary)
.font(.caption)
Spacer()
Text("Author_Name \(self.author)")
.foregroundColor(.secondary)
.font(.caption).onTapGesture {
}
}
Text("Quotes")
.font(.headline)
Text("Content")
.font(.body)
Text("\(likes) Like(s)")
.font(.subheadline)
}.frame(idealHeight: .greatestFiniteMagnitude)
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Debug for Error:
调试错误:
Mangling with verbatim Text initialiser, Text has two initialisers.
用逐字文本初始化程序处理,文本有两个初始化程序。
init(verbatim content: String) //this keeps string literal i.e. No localisation//Use For Localization
init(_ key: LocalizedStringKey,
tableName: String? = nil,
bundle: Bundle? = nil,
comment: StaticString? = nil)
Mangling with LocalizedStringKey initialiser. LocalizedStringKey has two to three initialisers. All with different purpose:
使用LocalizedStringKey 初始化程序进行处理。 LocalizedStringKey具有两到三个初始化程序。 都有不同的目的:
init(stringLiteral value: String)
//as parameter name suggest, it does not interpolate and try to
// to localize string as it is
//Text("Quotes") -> Works!
//Text("Author_Name \(self.author)") -> Will not Work.
//Text("\(self.likes) Like(s)") -> Will not Work.
_________________________________________________________init(_ value: String)
//All type of Localizable key work with this initialiser
_________________________________________________________init(stringInterpolation: LocalizedStringKey.StringInterpolation)
// this requires manual and
Wrong/Different Interpolation Value Type. The interpolation happens on compile-time and compiler may interpolate a variable in a different format. Which may result in broken Localization.
插值值类型错误/不同。 插值发生在编译时,编译器可能会以其他格式插值变量。 这可能会导致本地化失败。
let likes: UInt = 10
print(LocalizedStringKey("\(likes) Like(s)"))LocalizedStringKey(key: "%llu Like(s)", hasFormatting: true, arguments: [SwiftUI.LocalizedStringKey.FormatArgument(value: 10, formatter: nil)])
------------------------------------------------
let like = 10
print(LocalizedStringKey("\(like) Like(s)"))LocalizedStringKey(key: "%lld Like(s)", hasFormatting: true, arguments: [SwiftUI.LocalizedStringKey.FormatArgument(value: 10, formatter: nil)])//this will not localize as %lld is not part of our expected localizable key.
Limitations:
局限性:
SwiftUI canvas cannot render Interpolatable Localisables.
SwiftUI画布无法渲染可插值 Localisable。
//Text("Quotes") -> Works on canvas!
//Text("Author_Name \(self.author)") -> Will not render on canvas.
//Text("\(self.likes) Like(s)") -> Will not render on canvas.
Demo:
演示:
Reference:
参考:
翻译自: https://levelup.gitconnected.com/localization-with-swiftui-5abbeb275d5