Swift: How can I change the size of Thumb Image on UISlider based of the value of the slider?

Steven Schafer picture Steven Schafer · May 6, 2015 · Viewed 13.7k times · Source

I haven't found an answer for this in Swift.

I have a UISlider that changes the value of a brush size for a drawing app I'm making. I want the size of the thumb image to update depending on the value of the slider's thumb position.

Here's a screenshot of the slider for some context: enter image description here

I set the initial image of the thumb in viewDidLoad()

self.brushSizeSlider.setThumbImage(UIImage(named: "black"), forState: UIControlState.Normal)

and have an IBAction for the slider as follows:

    @IBAction func brushSizeSliderChanged(sender: UISlider) {
    if sender == brushSizeSlider {
        self.brushWidth = CGFloat(sender.value)
        println("the size of the brush is: \(self.brushWidth)")
    }
}

What should I add to brushSizeSliderChanged to change the size of it's thumb image depending on the value of brushSizeSliders thumb position / value?

Answer

Antony picture Antony · Sep 22, 2015
var ratio : CGFloat = CGFloat ( sender.value + 0.5)
var thumbImage : UIImage = UIImage(named: "yourImage")!
var size = CGSizeMake( thumbImage.size.width * ratio, thumbImage.size.height * ratio )
self.setThumbImage( self.imageWithImage(thumbImage, scaledToSize: size), forState: UIControlState.Normal )

Add this code to your action method