Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SF Rounded in UIKit

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.

like image 776
Hekes Pekes Avatar asked Jan 30 '20 08:01

Hekes Pekes


2 Answers

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)
like image 68
Kevin Avatar answered Oct 19 '22 09:10

Kevin


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)
like image 28
Artem Kirillov Avatar answered Oct 19 '22 11:10

Artem Kirillov