无法弄清楚这一点,通过下面的代码,我让用户在 a 上设置一个值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)
}
}