carlofacose
carlofacose

Reputation: 35

Make blink effect to the thumb in UISlider - Swift

I have to make that the thumb of my slider has a "blink" effect, but only the thumb not the whole slider. What I had thought is to use a timer that for example every 0.8 seconds lowers and raises the alpha value of the thumb.

var alpha = 1.0
timerAlpha = Timer.scheduledTimer(withTimeInterval: 0.8,repeats: true)
        {t in 
            self.slider.setThumbImage(thumb, for: UIControl.State(rawValue: UIControl.State.RawValue(alphaValue)))
            self.slider.alpha = CGFloat(alpha)
            if alpha == 1.0{
                alpha = 0.5
            }else{
                alpha = 1.0
            }
        }

But the problem is that this way I blink the whole slider and not ONLY the thumb. How do I make only the thumb blink

Upvotes: 1

Views: 194

Answers (2)

Sweeper
Sweeper

Reputation: 272760

Rather than setting the alpha of the whole slider, just use a more "faded" version of the thumb image.

First, you need to get a faded version of thumb:

let thumb = UIImage(...)! // create the thumb image as you did before
UIGraphicsBeginImageContextWithOptions(thumb.size, false, thumb.scale)
thumb.draw(at: .zero, blendMode: .normal, alpha: 0.5) // find an alpha value that you like
let fadedThumb = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

You'd probably want to put thumb and fadedThumb at the class level, so you don't recreate them every time the timer is triggered. Also, add a isUsingFadedThumb property to track the current state:

var isUsingFadedThumb = false

And then just:

Timer.scheduledTimer(withTimeInterval: 0.8,repeats: true)
    {_ in 
        if self.isUsingFadedThumb {
            self.slider.setThumbImage(thumb, for: .normal)
        } else {
            self.slider.setThumbImage(fadedThumb, for: .normal)
        }
        self.isUsingFadedThumb.toggle()
    }

Upvotes: 1

Tommy Sadiq Hinrichsen
Tommy Sadiq Hinrichsen

Reputation: 804

Make a custom slider where you create your own thumb imageview that follows value of the original slider.

This way you have full control of the thumb.

Upvotes: 0

Related Questions