不知道各位在用 Picker 的时候有没有遇到下面这个报错警告⚠️,导致 Menu 菜单选项无法进行选择
Called -[UIContextMenuInteraction updateVisibleMenuWithBlock:] while no context menu is visible. This won't do anything.
具体是这样的
class TestItem: ObservableObject {
@Published var option: Int = 0
}
....
@State var test = TestItem()
@State var optionType: Int = 0
Picker("测试", selection: $test.option) {// 1. 这里换成 $optionType 就不会报错
Text("选项一").tag(0)
Text("选项二").tag(1)
}
.pickerStyle(MenuPickerStyle())
// 2. 这里换成 WheelPickerStyle 或其他类型的就不会报错
程序可以正常跑起来,但是当点击这个 Picker 的时候,就会报开头的这个错误警告。
在 Reddit 上也看到有开发者遇到这个问题,但貌似没有提供解决方案,于是自己摸索了一下,解决的方案就是上面代码中的注释里提到的。
另外,由于我的项目里必须要用到 observedobject 这东西在不同的 View 直接进行状态传递,而且我必须要用 MenuPickerStyle 类型,因此最终的解决方案如下
class TestItem: ObservableObject {
@Published var option: Int = 0
}
....
@State var test = TestItem()
@State var optionType: Int = 0
Picker("测试", selection: $optionType) {
Text("选项一").tag(0)
Text("选项二").tag(1)
}
.pickerStyle(MenuPickerStyle())
.onChange(of: optionType, perform: { typeValue in
test.option = typeValue
})