swiftwatchkitwkinterfacecontroller

Why can't I send data between interface controllers for Apple Watch?


Basically, what I'm trying to do is pass an integer from one interface controller. The slider in the controller "SecondPage" will get an integer value from the slider and should send it to the interface controller called "ThirdPage" and set the title of that label to the value. I've tried so many methods but all to no avail. I'm just trying to send the context from the 2nd interface controller, receive it in the awake(withContext context: Any?) method in the 3rd controller and save it as the title until the slider is changed again.

Here's what I tried first in the second page controller, but it didn't pass any data:

override func contextForSegueWithIdentifier(segueIdentifier: String) -> AnyObject? {
if segueIdentifier == "ThirdPage"{
    return sliderval
}
return nil
}

here's what I tried after that, it passed the data but it doesn't "save" it. It pops up the interface controller with the updated label to the slider value, but I don't want it to pop up, I want that value to be saved to the label. When I close the pop up, and swipe right to the Third Page, the label is still called "Label"

self.presentController(withName: "ThirdPage", context: sliderval)

Here's some pictures of the output as well as some of my code. Any help is appreciated, thank you. PS: This is all in Swift 3enter image description here

enter image description here

enter image description here

enter image description here

enter image description here


Solution

  • You are using a page-based navigation, and you need to pass data between pages.

    What I would do is save the data from the slider somewhere that the third page can access, and populate the data in the label on willActivate. The willActivate method should be called by the system when the user swipes between pages.

    At the global scope, create a variable to hold the slider value.

    var sliderValue: Float = 0
    

    In your second interface controller, set this value when the slider changes.

    @IBAction func sliderChanged(_ value: Float) {
        sliderValue = value
    }
    

    In your third interface controller, when the page is about to appear, set the label to the correct value.

    override func willActivate() {
        label.setText("\(sliderValue)")
    }
    

    If you want to avoid the use of global variables you can read and write from user defaults, or use other tactics, but this will depend on the exact needs of your application.