Search code examples
swiftstoryboardwatchkitfont-sizeapple-watch

How can I scale font size based on watch size in WatchKit?


I have an Apple Watch app that I would like to scale the font size for depending on the screen size. Currently, the only way I found to scale the font size is based on setting the device variation for each size in the storyboard. However, I was wondering if there was a way around this. I'm hoping for a way to scale the font size based the on screen size automatically. Any tips or suggestions are appreciated.


Solution

  • You should multiply the font size with the current width of the screen and divide the product with a reference screen size of your choice (in this example, it's the 38mm size, which has the width of 136 logical pixels).

    let label = WKInterfaceLabel()
    
    let fontSize: CGFloat = 12
    let scaledFontSize = fontSize * WKInterfaceDevice.current.screenBounds.width / 136
    
    let font = UIFont.systemFont(ofSize: scaledFontSize)
    let attrString = NSAttributedString(string: "Example Text", attributes: [.font: font])
    label.setAttributedText(attrString)