Search code examples
swiftcrashwatchkituicolor

WatchKit setBackground Color Crash


After importing UIKit and attempting to toggle around with where to initialize the buttons colors programmatically, I can't seem to figure out why a crash occurs in the class conforming to WKInterfaceController

import UIKit
import WatchKit

class InterfaceController: WKInterfaceController {

  @IBOutlet fileprivate var myButton : WKInterfaceButton!

  override func willActivate() { // About to be visible to user
    super.willActivate()

    self.myButton.setBackgroundColor(UIColor.red) // CRASH
  }
}

enter image description here

enter image description here

enter image description here


Solution

  • The reason was in unused breakpoints.

    Anyway:

    Use awake(withContext:) for changing UI:

    When creating an interface controller, WatchKit instantiates the class and calls its init() method followed shortly by its awake(withContext:) method. Use those methods to initialize variables, load data, and configure the items in your storyboard scene. If WatchKit passes a valid object to the awake(withContext:) method, use the information in that object to customize the initialization process.

    You can't use willActivate() for changing background color etc.:

    The willActivate() method lets you know when your interface is active. Use the willActivate() method to perform any last minute tasks, such as checking for updates to your content. (Do not use it for your primarily initialization.)

    Also always use weak outlets:

      @IBOutlet fileprivate weak var myButton : WKInterfaceButton!
    

    And check that your outlet was connected.