Search code examples
iosswiftuilabeluislidermonospace

Strange behaviour with monospaced font in UILabel when changing text


I have a strange issue when using monospacedDigitSystemFont(ofSize:weight:)

I have one UISlider and one UILabel in my UIViewController. The Label is showing the current value of the slider + some description text. When changing the slider's value, the text of myLabel is shaking left and right a bit. I would expect the myLabel's text to not shake left and right, since I am using monospacedDigitSystemFont(ofSize:weight:).

This is my code:

import UIKit

class ExampleViewController: UIViewController {
    @IBOutlet weak var myLabel: UILabel!
    @IBOutlet weak var mySlider: UISlider!

    override func viewDidLoad() {
        super.viewDidLoad()
        myLabel.font = UIFont.monospacedDigitSystemFont(ofSize: 15, weight: .bold)
    }

    @IBAction func sliderChanged(_ sender: UISlider) {
        myLabel.text = String(format: "%.5f is the actual Value of the Slider", sender.value)
    }
}

GIF about the jiggle:

jiggling monospaced text

Any suggestions? Am I missing something?


Solution

  • This is a horrible bug and it's caused by the monospaced font being bold. Setting the weight to regular solves this problem.

    myLabel.font = UIFont.monospacedDigitSystemFont(ofSize: 15, weight: .regular)
    

    If you still want to use a bold font, consider using a non-standard monospaced font.