以编程方式设置WKPickerItem不会超过某个值?

时间:2018-01-29 03:01:59

标签: ios swift watchkit wkinterfacecontroller watch-os-4

无法解决这个问题,通过下面的代码我让用户在WKPickerItem上设置一个值,将其存储在UserDefaults中,然后在下次InterfaceController时将其加载加载并尝试使用存储的值设置PickerItem。问题是,如果我将值设置为1 - 7,然后导航回然后点击再次显示此接口控制器,我在InterfacePicker中看到正确的值。但是,如果我将其设置为8,9或10,InterfacePicker最多只能达到7?正确的索引和项目打印到控制台,它只是UI中的实际值是错误的?

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)

    }

}

1 个答案:

答案 0 :(得分:1)

尝试拨打

shiftTimerHapticIntervalPicker.setSelectedItemIndex(indexOfUserShiftTimerHapticInterval)

在InterfaceController的didAppear()函数中,而不是在willActivate()函数中。当我尝试在willActivate()函数中设置选择器的索引时,我看到了一些相同的东西,但更随机。