Search code examples
iosswiftfontsstoryboarduikit

How to implement UIKit: SF Pro Rounded?


Help pls, I searched around and can't find the solution to implement this; Rounded, The rounded variant of the default typeface.

Here's the sample code

//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let label = UILabel()
        label.frame = CGRect(x: 150, y: 200, width: 200, height: 32)
        label.text = "Hello World!"
        label.textColor = .black
        label.font = .systemFont(ofSize: 32, weight: .semibold)
        label.font.fontDescriptor.withDesign(.rounded) // I'm guessing this is wrong

        view.addSubview(label)
        self.view = view
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

Thanks


Solution

  • Well with the code from original answer (How to use SF Rounded font in SwiftUI?), you can use it in your code like this:

        override func loadView() {
        let view = UIView()
        view.backgroundColor = .white
    
        let label = UILabel()
        label.frame = CGRect(x: 150, y: 200, width: 200, height: 32)
        label.text = "Hello World!"
        label.textColor = .black
    
        // set rounded font
        let fontSize: CGFloat = 32
        let systemFont = UIFont.systemFont(ofSize: fontSize, weight: .semibold)
        let roundedFont: UIFont
        if let descriptor = systemFont.fontDescriptor.withDesign(.rounded) {
            roundedFont = UIFont(descriptor: descriptor, size: fontSize)
        } else {
            roundedFont = systemFont
        }
    
        label.font = roundedFont
    
        view.addSubview(label)
        self.view = view
    }
    

    But when you want to use it on multiple places, it would be better if you could reuse it... so for example I create class called FontKit ... which has static function, which gives me rounded font. Like this:

    class FontKit {
    
     static func roundedFont(ofSize fontSize: CGFloat, weight: UIFont.Weight) -> UIFont {
        let systemFont = UIFont.systemFont(ofSize: fontSize, weight: weight)
        let font: UIFont
    
        if #available(iOS 13.0, *) {
            if let descriptor = systemFont.fontDescriptor.withDesign(.rounded) {
                font = UIFont(descriptor: descriptor, size: fontSize)
            } else {
                font = systemFont
            }
        } else {
            font = systemFont
        }
    
        return font
    }
    }
    

    And then in my code I use it like this:

    label.font = FontKit.roundedFont(ofSize: 32, weight: .semibold)