I have a lot of localized texts written in my Localizable.strings file, and I am looking for a way to use these and get them shown in the interface builder. That is, instead of creating outlets for all my views and setting the text in code, I would like to make an IB_DESIGNABLE
UILabel subclass, which must access my Localizable.strings file and then show the localized text directly on the interface builder.
The problem is, that NSLocalizedString does not give any results in interface builder, but only when I actually run the code. Is there a way to tell the interface builder which file to use for localization (for example in prepareForInterfaceBuilder)?
Thanks to JRV's answer I finally fixed this class:
@IBDesignable class ALLocalizableLabel: UILabel {
@IBInspectable var localizeString:String = "" {
didSet {
#if TARGET_INTERFACE_BUILDER
var bundle = NSBundle(forClass: self.dynamicType)
self.text = bundle.localizedStringForKey(self.localizeString, value:"", table: nil)
#else
self.text = NSLocalizedString(self.localizeString, comment:"");
#endif
}
}
}
This creates the possibility to set the key in the interface builder:
This will update the label directly in the interface builder, quite cool and something xcode should support by default!
You can find this on Github as well: https://github.com/AvdLee/ALLocalizableLabel
I finally figured it out myself. The answer is: use [[NSBundle bundleForClass:self.class] localizedStringForKey:key value:@"" table:nil]
to get translations from the Localizable.strings file in interface builder. This realization made it possible for me to redefine the NSLocalizedString
macro (only for interface builder):
#if TARGET_INTERFACE_BUILDER
#undef NSLocalizedString
#define NSLocalizedString(key, comment) [[NSBundle bundleForClass:self.class] localizedStringForKey:key value:@"" table:nil]
#endif
This worked for me,
import Foundation
import UIKit
@IBDesignable
class YourLabel: UILabel {
@IBInspectable var stringLocalizationKey: String = ""{
didSet{
text = stringLocalizationKey.localized
setup()
}
}
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
func setup(){
textAlignment = NSTextAlignment.center
}
override open func layoutSubviews() {
super.layoutSubviews()
self.preferredMaxLayoutWidth = self.frame.size.width
self.layoutIfNeeded()
}
override func prepareForInterfaceBuilder() {
let bundle = Bundle(for: type(of: self))
self.text = bundle.localizedString(forKey: self.stringLocalizationKey, value:"", table: nil)
}
}
And add this String
extension:
extension String {
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With