我正在尝试使用新的 MenuBarExtra 在 Swift UI 中创建一个简单的额外菜单栏。我希望弹出窗口中的按钮文本在每次打开菜单时动态更新。
我正在像这样创建 MenuBarExtra 。
MenuBarExtra("Example menu title") {
Button("Item 1") {
}
Button("Item 2") {
}
Button("Item 3") {
}
}
Run Code Online (Sandbox Code Playgroud)
我希望每次打开菜单时按钮文本(即第 1 项)都会更改。我本来希望 onAppear 每次打开菜单时都会触发,但它只在第一次时触发。首次打开弹出窗口后,没有明确的方法来检测菜单关闭或打开事件。
我尝试使用各种事件处理回调来检测弹出窗口的打开。OnAppear 用于检测视图的初始创建,而 onDisappear 则从未被调用。
MenuBarExtra("Example menu title") {
VStack {
Button("Item 1") {
}
Button("Item 2") {
}
Button("Item 3") {
}
}.onAppear() {
print("This only prints the very first time the menu is opened")
}
}
Run Code Online (Sandbox Code Playgroud)