在 watchOS 2 界面 Controller 中,我显示了一个按钮和一个 WKInterfacePicker。
当用户按下按钮时,选择器会隐藏并显示动画。视觉效果很好。
这有一个意想不到的副作用:使用动画设置高度会更改所选项目,到目前为止我找不到解决方法。
func setDurationPickerVisibility(duration: NSTimeInterval) {
print ("self.durationPickerHidden=\(self.durationPickerHidden)")
animateWithDuration(duration) {
if self.durationPickerHidden {
self.durationPicker.resignFocus()
self.durationPicker.setHeight(0.0)
self.durationPicker.setHidden(self.durationPickerHidden)
} else {
self.durationPicker.setHeight(self.durationPickerHeigth)
print ("animation setting durationPicker Index to \(self.durationPickerIndex)")
self.durationPicker.setSelectedItemIndex(self.durationPickerIndex)
}
}
if !self.durationPickerHidden {
print ("direct setting durationPicker Index to \(self.durationPickerIndex)")
self.durationPicker.setSelectedItemIndex(durationPickerIndex)
self.durationPicker.setHidden(self.durationPickerHidden)
self.durationPicker.focus()
self.durationPicker.setSelectedItemIndex(durationPickerIndex)
}
}
@IBAction func durationPickerChanged(value: Int) {
print("durationPickerChanged: \(value)")
//...
}
运行此代码时,控制台显示以下输出:
self.durationPickerHidden=false
direct setting durationPicker Index to 24
animation setting durationPicker Index to 24
durationPickerChanged: 21
您看到选择器更改为我没有设置的索引 21。
我尝试了这段代码的许多变体,关键部分似乎如下:
- 当我在没有动画的情况下运行时,一切正常。 (选择索引 24)
- setFocus() 在动画内部还是外部都没有区别。
- setSelectedItemIndex 在动画内部还是外部都没有区别
- 当 self.durationPicker.setHeight(self.durationPickerHeigth) 在动画内部(这对视觉效果很关键)时,选择器选择这个任意项目 21。
有谁知道我如何设置带有动画的选择器的高度并且仍然控制哪个项目被选中?
最佳答案
我发现了以下使问题不可见的解决方法:
var durationPickerWorkaroundNecessary = false
func setDurationPickerVisibility(duration: NSTimeInterval) {
print ("self.durationPickerHidden=\(self.durationPickerHidden)")
animateWithDuration(duration) {
if self.durationPickerHidden {
self.durationPicker.resignFocus()
self.durationPicker.setHeight(0.0)
self.durationPicker.setHidden(self.durationPickerHidden)
} else {
self.durationPicker.setHeight(self.durationPickerHeigth)
print ("animation setting durationPicker Index to \(self.durationPickerIndex)")
self.durationPicker.setSelectedItemIndex(self.durationPickerIndex)
self.durationPicker.setHidden(self.durationPickerHidden)
self.durationPicker.focus()
self.durationPickerWorkaroundNecessary = true
}
}
}
@IBAction func durationPickerChanged(value: Int) {
print("durationPickerChanged: \(value)")
if durationPickerWorkaroundNecessary == true {
durationPickerWorkaroundNecessary = false
if durationPickerIndex != value {
print("durationPickerChanged: fixing value")
durationPicker.setSelectedItemIndex(durationPickerIndex)
return
}
}
durationPickerIndex = value
//...
}
基本思想是忽略动画后的第一个变化事件。 丑陋,但它有效。
在动画内部设置focus()可以让动画更流畅。
关于swift - 使用动画设置 WKInterfacePicker 高度选择任意项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33707802/