这应该很简单,但是我希望在条件为真时显示警报。(见下文)我已经看到很多地方,您使用按钮来触发警报,但是我只希望警报在条件发生时触发例如在简单的“ If”语句中满足。加载代码后应立即显示。
import SwiftUI
struct ContentView: View {
@State private var showingAlert = false
var score = 3
var body: some View {
VStack{
if score == 3 {
showingAlert = true
} .alert(isPresented: $showingAlert) {
Alert(title: Text("Hello SwiftUI!"), message: Text("This is some detail message"), dismissButton: .default(Text("OK")))
}
}
}
答案 0 :(得分:0)
您可以在视图的init()
方法中检查条件是否成立,然后设置showingAlert
的初始值。
struct ContentView: View {
@State private var showingAlert = false
var score = 3
init()
{
//check if condition is true
if (true)
{
self._showingAlert = State(initialValue: true)
}
}
var body: some View {
VStack{
EmptyView()
} .alert(isPresented: self.$showingAlert) {
Alert(title: Text("Hello SwiftUI!"), message: Text("This is some detail message"), dismissButton: .default(Text("OK")))
}
}
}