实现App国际化时,如何保留UILabel的自定义字体?
Hey there! Let’s tackle your localization + custom UILabel font questions step by step—this is a common scenario, and there are straightforward ways to keep your fonts intact while making your app multilingual.
First, let’s clarify: localization and font settings are separate concerns, so you don’t have to worry about localization overriding your fonts by default. Here’s how to handle both your Storyboard and code-based labels:
Storyboard-Based UILabels
- When you localize your Storyboard (generating
.storyboardstringsfiles for each language), these files only control the text content of your labels—not their font, color, or layout properties. - Just set your custom font directly in the Storyboard’s Attributes Inspector, then update the corresponding entry in your
.storyboardstringsfile (e.g.,"fxV-9K-0dL.text" = "Bonjour!";). The font you set in the Storyboard will stay applied automatically.
Code-Based UILabels
For labels you create or reference in Swift code:
- First, set your custom font as you normally would:
myCustomLabel.font = UIFont(name: "YourCustomFont-Regular", size: 16) - Then assign the localized text using
NSLocalizedString:myCustomLabel.text = NSLocalizedString("greeting_message", comment: "Main screen welcome text")
The font property is independent of the text content, so replacing the text with a localized string won’t touch your font settings.
To streamline this process (and avoid repeating NSLocalizedString calls everywhere), create a reusable UILabel subclass that handles both localization and custom fonts out of the box. This is the cleanest approach for larger apps or if you have many custom labels.
Here’s a complete implementation:
import UIKit class LocalizedCustomFontLabel: UILabel { // IBInspectable lets you set these properties directly in Storyboard @IBInspectable var localizationKey: String? { didSet { updateLocalizedText() } } @IBInspectable var customFontName: String = "YourDefaultCustomFont" { didSet { updateFont() } } @IBInspectable var customFontSize: CGFloat = 16 { didSet { updateFont() } } override func awakeFromNib() { super.awakeFromNib() // Initialize font and localized text when the label loads from Storyboard updateFont() updateLocalizedText() } private func updateLocalizedText() { guard let key = localizationKey else { return } text = NSLocalizedString(key, comment: "Localized text for key: \(key)") } private func updateFont() { // Fall back to system font if custom font isn't found let desiredFont = UIFont(name: customFontName, size: customFontSize) ?? UIFont.systemFont(ofSize: customFontSize) font = desiredFont // Optional: Support dynamic type (adjusts with system font size) adjustsFontForContentSizeCategory = true font = UIFontMetrics(forTextStyle: .body).scaledFont(for: desiredFont) } }
How to Use This Subclass
In Storyboard:
- Add a UILabel to your view, then set its class to
LocalizedCustomFontLabelin the Identity Inspector. - In the Attributes Inspector, you’ll see new fields:
- Localization Key: Enter the key from your
Localizable.stringsfile. - Custom Font Name: Type the exact name of your custom font (check your
Info.plistor useUIFont.familyNames()to verify). - Custom Font Size: Set your desired font size.
- Localization Key: Enter the key from your
- That’s it—no code needed! The label will automatically load the localized text and apply your custom font.
In Code:
let welcomeLabel = LocalizedCustomFontLabel() welcomeLabel.localizationKey = "welcome_message" welcomeLabel.customFontName = "YourCustomFont-Bold" welcomeLabel.customFontSize = 18 // Add constraints and add to view as usual view.addSubview(welcomeLabel)
- Make sure your custom fonts are properly added to your project: include them in your target, and add their filenames to the
Fonts provided by applicationarray in yourInfo.plist. - If you need different text styles (e.g., body, headline), adjust the
UIFontMetricstext style in theupdateFont()method to match your needs.
内容的提问来源于stack exchange,提问作者Ben

