英文:
How can I show an alert on a button click of a menu
问题
菜单{
Button("个人资料", action: {})
Button("设置", action: {})
Button(action: {
self.showingAlert = true
}, label: {
Text("注销")
})
} label: {
Button(action: {
}) {
Image("icon-menu").imageScale(.large)
}
}.alert(isPresented:$showingAlert){
Alert(title: Text("注销?"), message: Text("确定要注销吗?"), primaryButton: .default(Text("确定"), action: {
}), secondaryButton: .cancel())
}
注:Alert 在注销按钮点击时未显示。有人可以帮忙吗?
我需要在菜单项点击时显示一个提示框,但它不起作用。
英文:
Menu{
Button("Profile", action: {})
Button("Settings", action: {})
Button(action: {
self.showingAlert = true
}, label: {
Text("Logout")
})
} label: {
Button(action: {
}) {
Image( "icon-menu").imageScale(.large)
}
}.alert(isPresented:$showingAlert){
Alert(title: Text("Logout?"), message: Text("Are you sure you want to logout?"), primaryButton: .default(Text("Ok"), action: {
}), secondaryButton: .cancel())
}
Alert is not showing on the click of logout. Can someone help on this
I need to show an alert on the click of a menu item. But it is not working
答案1
得分: 0
创建一个用于注销操作的函数。
struct ContentView: View {
var body: some View {
Menu {
Button("个人资料", action: {})
Button("设置", action: {})
Button("注销", action: logoutAction)
}
}
func logoutAction() {
// 在这里添加与提醒相关的调用
}
}
英文:
Create one function for logout action
struct ContentView: View {
var body: some View {
Menu{
Button("Profile", action: {})
Button("Settings", action: {})
Button("Logout", action: logoutAction)
}
}
func logoutAction() {
}}
Add your alert related call inside logoutAction method
答案2
得分: 0
你的代码对我来说运行得很好。这是我用于测试的代码,在真实设备上运行,iOS 16.3 和带有 macOS 13.2 的 macCatalyst。
struct ContentView: View {
@State var showingAlert = false
var body: some View {
Menu {
Button("Profile", action: {})
Button("Settings", action: {})
Button(action: { showingAlert = true }, label: {
Text("Logout")
})
} label: {
Button(action: { }) {
Image(systemName: "ellipsis.circle").imageScale(.large)
}
}.alert(isPresented:$showingAlert){
Alert(title: Text("Logout?"),
message: Text("Are you sure you want to logout?"),
primaryButton: .default(Text("Ok"), action: { }),
secondaryButton: .cancel())
}
}
}
如果你需要进一步的帮助,请告诉我。
英文:
your code works well for me. This is the code I used for testing, on real devices ios 16.3 and macCatalyst with macos 13.2
struct ContentView: View {
@State var showingAlert = false
var body: some View {
Menu {
Button("Profile", action: {})
Button("Settings", action: {})
Button(action: { showingAlert = true }, label: {
Text("Logout")
})
} label: {
Button(action: { }) {
Image(systemName: "ellipsis.circle").imageScale(.large)
}
}.alert(isPresented:$showingAlert){
Alert(title: Text("Logout?"),
message: Text("Are you sure you want to logout?"),
primaryButton: .default(Text("Ok"), action: { }),
secondaryButton: .cancel())
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论