The font changes when I’m trying to localize UIButtons. The localization itself works; I can see the language changing but the font is changing too I tried localizing using base internationalization, localized strings and different pods and the font still changes. I created the UIButtons using the interface builder and set the font in interface builder too, and also tried creating the UIButton programmatically but the font still changes. It only changes for UIButtons, I don’t have this problem with UILabels or UITexfields.
This is what the UIButton looks like before localization:
This is what the UIButton looks like after localization:
This is the code that I use to set the button and localize it programmatically:
@IBOutlet weak var button1: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
button1.titleLabel?.font = UIFont(name: "Helvetica Bold", size: 20)
button1.setAttributedTitle(NSAttributedString(string: NSLocalizedString("button1", comment: "")), for: .normal)
}
For localization using the interface builder, I used a pod where you can give a UI element a localized key, but the same issue arises.
CodePudding user response:
UIButton
objects can be configured in two primary ways:
- Traditionally, via setting attributes on the button and its labels directly (as you do in the code above), or
- As of iOS 15, via
UIButton.configuration
to set multiple properties all at once
Although this doesn't appear to be documented overly clearly, when you set a configuration
on a button, those properties override anything which you might assign yourself to the button's properties. In the case of iOS projects created for iOS 15 , buttons created in storyboards default to being set up with a button configuration in the Attributes inspector: the Plain, Filled, Gray, and Tinted "style" options offered correspond to the static plain()
, filled()
, gray()
, and tinted()
default button configurations offered by UIButton.Configuration
.
When one of these styles is set on the UIButton
in the storyboard, the properties you attempt to set in code are overridden by its configuration. You have two main options:
- Set the button style to Default in the storyboard, which avoids applying a configuration to the button, and allowing you to use the traditional properties to style the button, or
- Style the button using its configuration instead
For apps which target iOS versions lower than iOS 15, (1) is the only option (and should be the default in storyboards anyway); but if you choose to go with (2), the configuration equivalent can look something like:
var attributes = AttributeContainer()
attributes.font = UIFont(name: "Helvetica Bold", size: 20)
let title = AttributedString(NSLocalizedString("button1", comment: ""), attributes: attributes)
button1.configuration.attributedTitle = title