问题
I want to use different fonts up to Languages each.
for example, roboto in English, openSans in French.
Localization
arrayOfTitle = [NSLocalizedString("comment", comment: "0"), NSLocalizedString("profile", comment: "1"), NSLocalizedString("Like", comment: "2")]
patterns using String 1.
let username: String? = (rList[indexPath.row].userInfo?.name)!
let attrString = NSMutableAttributedString(string: username!,
attributes: [NSFontAttributeName: UIFont(name: "Roboto-Bold", size: 12.0)!])
attrString.append(NSMutableAttributedString(string: rList[indexPath.row].gender,
attributes: [NSFontAttributeName: UIFont(name: "Roboto", size: 12.0)!]))
cell.label.attributedText = attrString
patterns using String 2.
customButton.setTitle("edit", for: .normal)
Thank you.
回答1:
As I can see, there you have 3 tasks to do.
- Map font name with current language code
- Get regular font from the name
- Get bold font from the name (optionally, but spotted from your code)
1. Map font name with current language code
In order to do that you need to get that code and write a switch statement.
It can look like this (may vary depending on your needs)
func languageCode() -> String? {
return NSLocale.autoupdatingCurrent.languageCode
}
func localizedFontName() -> String {
let defaultFont = "Arial"
guard let code = languageCode() else {
return defaultFont
}
switch(code) {
case "en":
return "Helvetica"
case "fr":
return "Menlo"
default:
return defaultFont
}
}
Please refer to NSLocale documentation for more info.
2. Get regular font from the name
It can be achieved by using UIFontDescriptor
let DefaultFontSize: CGFloat = 12.0
func font(from name: String) -> UIFont {
let descriptor = UIFontDescriptor(name: name, size: DefaultFontSize)
return UIFont(descriptor: descriptor, size: DefaultFontSize)
}
3. Get bold font from the name
And the last task can be done via UIFontDescriptor
as well.
let BoldFontSize: CGFloat = 12.0
func boldFont(from name: String) -> UIFont {
let regularFont = font(from: name)
guard let descriptor = regularFont.fontDescriptor
.withSymbolicTraits(.traitBold) else {
return regularFont
}
return UIFont(descriptor: descriptor, size: BoldFontSize)
}
Ultimately it all can be used like this:
let nameFont = boldFont(from: localizedFontName())
let nameString = NSAttributedString(string: "username ",
attributes: [NSFontAttributeName: nameFont])
let surnameFont = font(from: localizedFontName())
let surnameString = NSAttributedString(string: "gender",
attributes: [NSFontAttributeName: surnameFont])
Complete Playground can be found here playground.zip
Hope that helps!
来源:https://stackoverflow.com/questions/43842029/swift3-different-font-in-the-all-of-the-uiview-with-localization-each