SwiftUI warning: Attempting -[UIContextMenuInteraction dismissMenu], when not in an active state
[Solution]
原始问题: UI 警告:`Attempting - [UIContextMenuInteraction disMenu], 如果没有活跃的国家,“。
这一警告信息与使用<代码>有关。 UIContextMenuInteraction in ImmediateUI. 通常的情况是,在你不处于积极状态时,就会出现这种情况。 这种警告往往是在一定寿命期间使用<条码>dismiss()方法不止一次造成的。
In your case, the warning is triggered when you press the "Back" button in the NavigationView
. This is because the UIContextMenuInteraction
associated with the context menu is still active when you navigate back, and SwiftUI is attempting to dismiss it.
To resolve this warning, you can explicitly handle the dismissal of the context menu when the view disappears. You can achieve this by implementing the onDisappear
modifier on the gameScreen
view and calling the dismiss()
method on the UIContextMenuInteraction
:
var body: some View {
NavigationView {
NavigationLink(destination: gameScreen) {
Text("Start game")
}
}
}
struct gameScreen: View {
@State private var contextMenuInteraction: UIContextMenuInteraction?
var body: some View {
Text("Game Screen")
.onAppear {
self.contextMenuInteraction = UIContextMenuInteraction(delegate: self)
UIApplication.shared.keyWindow?.addInteraction(self.contextMenuInteraction!)
}
.onDisappear {
self.contextMenuInteraction?.dismiss()
UIApplication.shared.keyWindow?.removeInteraction(self.contextMenuInteraction!)
}
}
}
extension gameScreen: UIContextMenuInteractionDelegate {
// Implement the necessary delegate methods for the context menu interaction
// ...
}
By explicitly dismissing the context menu in the onDisappear
modifier, you ensure that the dismissal is only called once during the lifecycle of the view, preventing the warning from being triggered.
请注意,该警告是Xcode 12 beta所特有的,可能不出现在Xcode 11.5或以前的版本中。 处理警告和错误,确保你的法典的稳定性和正确性,始终是一种良好做法。