Search code examples
xcodeswiftwatchkitwatchos-2

How can I sum WKInterfaceSlider values?


I want to know how can I sum the values of 2 WKInterfaceSlider.

This is the entire code I've done so far:

@IBOutlet weak var label1: WKInterfaceLabel!
@IBOutlet weak var slider1: WKInterfaceSlider!

@IBOutlet weak var label2: WKInterfaceLabel!
@IBOutlet weak var slider2: WKInterfaceSlider!


@IBAction func sliderValueChanged(value: Float)
{
    let roundedValue = Int(round(value))
    self.label1.setText("\(roundedValue)")
}

@IBAction func slider2ValueChanged(value: Float)
{
    let roundedValue = Int(round(value))
    self.label2.setText("\(roundedValue)")
}

@IBAction func calculos()
{
    var result = slider1.value + slider2.value
    self.result.setText("\(result)")
}

Xcode wont compile it, there is an ! that says

Value of type 'WKInterfaceSlider' has no member 'value'.


Solution

  • On WatchOS you have no way to read the slider value, you have to keep it track of it by yourself:

    var sliderOneValue : Int = 0 // if you set starting values in the interface builder, you need to set them here as well
    var sliderTwoValue : Int = 0 
    
    @IBAction func sliderValueChanged(value: Float) {
        sliderOneValue = Int(round(value))
        self.label1.setText("\(sliderOneValue)")
    }
    
    @IBAction func slider2ValueChanged(value: Float) {
        sliderTwoValue = Int(round(value))
        self.label2.setText("\(sliderTwoValue)")
    }
    
    @IBAction func calculos() {
        let result = sliderOneValue + sliderTwoValue
        self.result.setText("\(result)")
    }
    

    The apple docs state

    When the user changes the value of a slider, WatchKit delivers the new value to the slider’s action method. The format of a slider’s action method is as follows:

    @IBAction func sliderAction(value: Float)

    Declare a method of this form in the interface controller class used to receive the slider’s new value. You can change the method name to anything you like. When configuring the slider in Xcode, connect its selector to your custom action method.