根据变量 name
的值,我需要显示一个警报,如果它是空的,它必须向我显示一个警报,如果它们包含值,它必须向我显示另一个不同的警报,我的代码我正在使用的是以下内容:
struct ContentView : View {
var name = ""
@State private var showAlert = false
@State private var showAlertok = false
var alert: Alert {
Alert(title: Text("Error"), message: Text("it is empty"), dismissButton: .default(Text("OK")) )
}
var alertok: Alert {
Alert(title: Text("Message"), message: Text("It's not empty"), dismissButton: .default(Text("Ok")) {
// here action
print("OK button tapped")
})
}
var body: some View {
VStack {
Text("Title")
Button(action: {
if self.name.isEmpty {
print("it is empty")
self.showAlert.toggle()
} else {
print("It's not empty")
self.showAlertok.toggle()
}
}) {
HStack{
Image(systemName: "arrow.right.circle.fill")
Text("SEND")
.padding(.horizontal)
}
.padding()
.foregroundColor(Color.white)
.background(Color.purple)
.cornerRadius(.infinity)
} .alert(isPresented: $showAlert, content: { self.alert })
.alert(isPresented: $showAlertok, content: { self.alertok })
}
}
}
在前面的代码中,如果 name
为空,则警报不起作用,它只会在控制台上显示 print("it is empty")
的值.如果 name
的值包含一个值,则显示警报。
我的代码哪里出错了?
最佳答案
我想当您像 SwiftUI 那样编写代码时接受最后一个,您会看到“非空警报”。但是如果你只写一个“.alert” block ,你就可以同时看到你的警报。这是我的解决方案。
struct ContentView : View {
var name = ""
@State private var showAlert = false
var alert: Alert {
Alert(title: Text("Error"), message: Text("it is empty"), dismissButton: .default(Text("OK")) )
}
var alertok: Alert {
Alert(title: Text("Message"), message: Text("It's not empty"), dismissButton: .default(Text("Ok")) {
// here action
print("OK button tapped")
})
}
var body: some View {
VStack {
Text("Title")
Button(action: {
self.showAlert.toggle()
}) {
HStack{
Image(systemName: "arrow.right.circle.fill")
Text("SEND")
.padding(.horizontal)
}
.padding()
.foregroundColor(Color.white)
.background(Color.purple)
.cornerRadius(.infinity)
}
.alert(isPresented: $showAlert, content: { name.isEmpty ? self.alert : self.alertok })
}
}
}
关于ios - 根据 'if' 语句发出警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58444372/