Search code examples
swiftcocoabindingslidernsslider

NSSlider: how to send value and action at the same time?


I thought it would be simple, but seemingly it´s not. I have a NSSlider from which the value I want to be shown in a label, like in this picture. With a setup as shown in this picture it´s working fine, using a binding takeIntValueFrom. Now I want this slider to set a new UserDefaults value:

 @IBAction func sliderAction(_ sender: NSSlider) {

        UserDefaults.standard.set(sliderOutlet.intValue, forKey: "sliderkey")

        print(UserDefaults.standard.integer(forKey: "sliderkey"))
    }

This actionfunc removes the takeIntValueFrom-binding. So in the end, it´s either or. Till now, I could not find a solution how to make it both work. Would be a pleasure to get some ideas.


Solution

  • Set the value of the label in sliderAction.

    Or, for the more adventurous, bind (Bindings Inspector) the value of the slider and the value of the label to the Shared User Defaults Controller with the same key path. The action of the slider is not connected.