iosswiftwatchkitwkinterfacecontrollerwatchos-4

Programmatically setting WKPickerItem won't go above a certain value?


Can't figure this out, via the code below I let the user set a value on a WKPickerItem, store it in UserDefaults, then load it up the next time the InterfaceController is loaded and attempt to set the PickerItem with the stored value. The problem is, if I set the value to 1 - 7, then navigate back then tap to show this Interface controller again, I see the correct value in the InterfacePicker. However, if I set it to 8, 9, or 10, the InterfacePicker will only go up to 7? the correct index and item print to the console, it’s just the actual value in the UI is wrong?

import WatchKit
import Foundation


class SettingsInterfaceController: WKInterfaceController {

    let defaults = UserDefaults.standard


    var shiftTimerHapticIntervalOptions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    var userShiftTimerHapticInterval = 10


    @IBOutlet var shiftTimerHapticIntervalPicker: WKInterfacePicker!


    @IBAction func shiftTimerHapticIntervalDidChange(_ value: Int) {
         WKInterfaceDevice.current().play(.click)
        userShiftTimerHapticInterval = shiftTimerHapticIntervalOptions[value]
    }


    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        let shiftTimerHapticIntervalPickerItems: [WKPickerItem] = shiftTimerHapticIntervalOptions.map {
            let pickerItem = WKPickerItem()
            pickerItem.caption = $0.description
            pickerItem.title = $0.description
            return pickerItem
        }

        shiftTimerHapticIntervalPicker.setItems(shiftTimerHapticIntervalPickerItems)

    }

    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()

        // Look up user settings

        if let userShiftTimerHapticIntervalUnwrapped = defaults.value(forKey: userShiftTimerHapticIntervalKey) as? Int {
            userShiftTimerHapticInterval = userShiftTimerHapticIntervalUnwrapped
            if let indexOfUserShiftTimerHapticInterval = shiftTimerHapticIntervalOptions.index(of: userShiftTimerHapticInterval) {                shiftTimerHapticIntervalPicker.setSelectedItemIndex(indexOfUserShiftTimerHapticInterval)
            }
        }
    }

    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()

        defaults.set(userShiftTimerHapticInterval, forKey: userShiftTimerHapticIntervalKey)

    }

}

Solution

  • Try calling

    shiftTimerHapticIntervalPicker.setSelectedItemIndex(indexOfUserShiftTimerHapticInterval)
    

    in the the InterfaceController's didAppear() function instead of in the willActivate() function. I saw some of the same things, but more random, when trying to set the picker's index in the willActivate() function.