Swift - shortcut not updating in WatchKit from delegate callback

I know the first question will be "are you using the code on the main thread" and the answer is "yes" I am.

I have a controller interface representing a modal and I am using a delegate callback to dismiss the modal and update the text label. Here's the code:

Delegate announced

// SetFooInterfaceController.swift
protocol SetFooInterfaceControllerDelegate: class {
  func setFooInterfaceControllerDelegateDidTapSetFoo(foo: Int)
}

      

And the presented VC is passed as context, so the delegate can be set:

// SetFooInterfaceController.swift
weak var delegate: SetFooInterfaceControllerDelegate?

override func awakeWithContext(context: AnyObject?) {
  super.awakeWithContext(context)

  if let presentingVC = context as? FooDetailInterfaceController {
    delegate = presentingVC
  }
}

      

When the button is clicked, the delegate is called:

// SetFooInterfaceController.swift
@IBAction func setWeightButtonTapped() {
  delegate?.setFooInterfaceControllerDelegateDidTapSetFoo(foo)
}

      

And the delegate method is called in the view of the view controller:

// FooDetailInterfaceController.swift
func setFooInterfaceControllerDelegateDidTapSetFoo(foo: Int) {
  dispatch_async(dispatch_get_main_queue(), {
    self.fooLabel.setText(String(foo))
    self.dismissController()
  })
}

      

Now the modal is rejected, setting breakpoints here shows that it actually reaches that point and all the variables exist. But the label just doesn't update. For example, calling the same method setText

in willActivate

updates it correctly. It is only when returning from this call to the delegate it is not. I also meet in a similar place elsewhere in the application.

+3


source to share


1 answer


You can only update interface elements during initialization and when the interface controller is considered "active". A is WKInterfaceController

active between calls willActivate

and didDeactivate

. In particular, you can update the interface in willActivate

, but you cannot update it in time didDeactivate

.

When you call your delegate, it will have to be sure to do the requested update when you call it willActivate

. This will happen as soon as the mod deviates.



You can find out about this in your WatchKit Controller watch lifecycle .

+6


source







All Articles