Search code examples
iosswiftuislider

Changing font size by using UISlider


I can't get this to work, and this code is not inside viewDidLoad()

@IBOutlet weak var label: UILabel!
@IBOutlet weak var slider: UISlider!

@IBAction func slider(sender: UISlider) {
    let senderValue = CGFloat(sender.value)
    label?.font = UIFont(name: (label?.font.fontName)!, size:senderValue * 20)
    label?.sizeToFit()

}

If you could help in any way that would be great.

screenshot


Solution

  • The code does not have to be inside viewDidLoad.

    Do you use autoLayout to position your view?

    This should work:

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var slider: UISlider!
    
    @IBAction func sliderAction(sender: AnyObject) {
        print("Slider value \(slider.value)")
    
        self.label.font = UIFont.systemFontOfSize(CGFloat(slider.value * 20.0))
    }
    

    Check if:

    • UIFont object is initialised correctly.
    • Remove label?.sizeToFit. Normally, the label text is drawn with the font you specify in the font property.
    • Constraints are correctly set on the UILabel object.