SwiftUI Alert

单个选项的alert

struct ContentView: View {
    @State private var showingAlert = false

    var body: some View {
        Button(action: {
            self.showingAlert = true
        }) {
            Text("Show Alert")
        }
        .alert(isPresented: $showingAlert) {
            Alert(title: Text("Important message"), 
            message: Text("Wear sunscreen"),
             dismissButton: .default(Text("Got it!"))
             )
        }
    }
}

两个且有action的alert

struct ContentView: View {
    @State private var showingAlert = false

    var body: some View {
        Button(action: {
            self.showingAlert = true
        }) {
            Text("清除回收站")
        }
        .alert(isPresented: $showAlert) {
            Alert(title: Text("你确定要清空回收站吗?"),
                  message: Text("任务将无法恢复"),
                  primaryButton: .destructive(Text("确定")) {
                    for todo in self.userData.userTodos {
                        if todo.isDeleted {
                            let todoIndex = self.userData.userTodos.firstIndex(where: {$0.id == todo.id})!
                            self.userData.userTodos.remove(at: todoIndex)
                        }
                    }
            },
                secondaryButton: .cancel(Text("取消")))
        }
    }
}
发布了19 篇原创文章 · 获赞 8 · 访问量 1446

猜你喜欢

转载自blog.csdn.net/qq_44864362/article/details/104162832