How to animate NSSlider value change in Cocoa application using Swift

391 views Asked by At

How do I animate NSSlider value change so it looks continuous? I tried using NSAnimation context

  private func moveSlider(videoTime: VLCTime) {
    DispatchQueue.main.async { [weak self] in
        NSAnimationContext.beginGrouping()
        NSAnimationContext.current.duration = 1
        self?.playerControls.seekSlider.animator().intValue = videoTime.intValue
        NSAnimationContext.endGrouping()
    }
}

My NSSlider still does not move smoothly.

To put you into the picture, I am trying to make a video player which uses NSSlider for scrubbing through the movie. That slider should also move as the video goes on. As I said, it does move but I can not get it to move smoothly.

1

There are 1 answers

1
Marc T. On BEST ANSWER

There is an Apple sample code in objective-C for exactly what you are looking for. Below how it would look like in Swift.

Basically you need an extension on NSSlider

extension NSSlider {

    override open class func defaultAnimation(forKey key: NSAnimatablePropertyKey) -> Any?{

        if key == "floatValue"{
            return CABasicAnimation()
        }else {
            return super.defaultAnimation(forKey: key)
        }
    }
}

Then you can simply use something like this in your move slider function.

private func moveSlider(videoTime: Float) {

        NSAnimationContext.beginGrouping()
        NSAnimationContext.current.duration = 0.5
        slider.animator().floatValue = videoTime
        NSAnimationContext.endGrouping()

}