Type 1: System language
Step 1: create a String Extension
import Foundation
extension String{
func localized() -> String {
NSLocalizedString(self,
tableName: "Localizable",
bundle: .main,
value: self,
comment: self)
}
}
Step 2: each string use the localized version
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello".localized())
.font(.largeTitle)
}
}
Step 3: Add translation files. Create Localizable.strings
// English
"Hello" = "Hello";
// Spanish
"Hello" = "Hola";
Step 4: App / Info / Localizations add relevant languages
Step 4: change app language to test the effect.
Edit Schema / Options / App Language
Type 2: per-app language
UserDefaults.standard has AppleLangauges
value to access system language, but this value cannot be changed.
Following steps show how to set per-app localization
Step 1: add app support languages
Step 2: add language transcripts
Step 3: code
ContentView.swift (The keypoint is Text(value, bundle: )
)
struct ContentView: View {
@EnvironmentObject var home: HomeGlobal
var body: some View {
Text("Visit Apple", bundle: home.bundle)
.onTapGesture {
changeLanguage()
}
}
func changeLanguage() {
print(#function)
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.home.lang = self.home.lang == "hi" ? "en" : "hi"
self.changeLanguage()
}
}
}
HomeGlobal.swift (return the bundle of the language)
class HomeGlobal: ObservableObject {
// Localization
@Published var lang: String = "hi"
var bundle: Bundle? {
let b = Bundle.main.path(forResource: lang, ofType: "lproj")!
return Bundle(path: b)
}
}