This is an improvement on the ".localized" approach. Start with adding the class extension as this will help with any strings you were setting programatically:
extension String {
func localized (bundle: Bundle = .main, tableName: String = "Localizable") -> String {
return NSLocalizedString(self, tableName: tableName, value: "\(self)", comment: "")
}
}
Example use for strings you set programmatically:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Now Xcode's storyboard translation files make the file manager messy and don't handle updates to the storyboard well either. A better approach is to create a new basic label class and assign it to all your storyboard labels:
class BasicLabel: UILabel {
//initWithFrame to init view from code
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
//initWithCode to init view from xib or storyboard
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
//common func to init our view
private func setupView() {
let storyboardText = self.text
text = storyboardText?.localized()
}
}
Now every label you add and provide default default for in the storyboard will automatically get translated, assuming you've provide a translation for it.
You could do the same for UIButton:
class BasicBtn: UIButton {
//initWithFrame to init view from code
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
//initWithCode to init view from xib or storyboard
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
//common func to init our view
private func setupView() {
let storyboardText = self.titleLabel?.text
let lclTxt = storyboardText?.localized()
setTitle(lclTxt, for: .normal)
}
}