Reputation: 1335
I have got a label and I spent quite a lot time trying to change the font of my UILabel to SF Rounded Bold.
Things like titleLabel.font = UIFont(name: "SFRounded-Bold", size: 34.0)
or titleLabel.font = UIFont(name: "SanFranciscoRounded-Bold ", size: 34.0)
don't work.
Is it even possible to use SF Rounded in UIKit? It is not listed in fonts list in scene editor and no one ever asked how to use it but in SwiftUI I can use SF Rounded without any problem.
Upvotes: 13
Views: 6829
Reputation: 14935
Expanding on Artem's answer:
extension UIFont {
func rounded() -> UIFont {
guard let descriptor = fontDescriptor.withDesign(.rounded) else {
return self
}
return UIFont(descriptor: descriptor, size: pointSize)
}
}
Now you can add .rounded()
to any font to get its rounded variant if it exists.
Upvotes: 3
Reputation: 1398
More concise version of Kevin's answer:
import UIKit
extension UIFont {
class func rounded(ofSize size: CGFloat, weight: UIFont.Weight) -> UIFont {
let systemFont = UIFont.systemFont(ofSize: size, weight: weight)
guard #available(iOS 13.0, *), let descriptor = systemFont.fontDescriptor.withDesign(.rounded) else { return systemFont }
return UIFont(descriptor: descriptor, size: size)
}
}
Usage:
let label = UILabel()
label.font = .rounded(ofSize: 16, weight: .regular)
Upvotes: 9
Reputation: 331
Swift 5, iOS 13+
Here's an extension version of the other post's answer
import UIKit
extension UIFont {
class func rounded(ofSize size: CGFloat, weight: UIFont.Weight) -> UIFont {
let systemFont = UIFont.systemFont(ofSize: size, weight: weight)
let font: UIFont
if let descriptor = systemFont.fontDescriptor.withDesign(.rounded) {
font = UIFont(descriptor: descriptor, size: size)
} else {
font = systemFont
}
return font
}
}
To use it:
let label = UILabel()
label.text = "Hello world!"
label.font = .rounded(ofSize: 16, weight: .regular)
Upvotes: 23