SwiftUI同一按钮的多个警报[重复]
Posted
技术标签:
【中文标题】SwiftUI同一按钮的多个警报[重复]【英文标题】:SwiftUI Multiple alerts for same button [duplicate] 【发布时间】:2020-07-04 22:06:42 【问题描述】:以下代码仅显示错误警报。有没有办法让警报匹配 IF 条件?
@State var showTrueAlert = false
@State var showFalseAlert = false
var body: some View
Button(action:
let isTrue = Bool.random()
if isTrue
self.showTrueAlert = true
print("True Alert")
else
self.showFalseAlert = true
print("False Alert")
)
Text("Random Alert")
.font(.largeTitle)
.alert(isPresented: $showTrueAlert)
Alert(title: Text("True"))
.alert(isPresented: $showFalseAlert)
Alert(title: Text("False"))
【问题讨论】:
这能回答你的问题吗? How can I have two alerts on one view in SwiftUI? 是的。这些链接非常有用。谢谢 【参考方案1】:您只能将.alert
应用于视图一次。创建一个仅处理警报当前状态的状态,然后创建两个变量来决定是否按下了假或真。 (也可能只将其存储在一个变量中)
struct ContentView6: View
@State var showAlert : Bool = false
@State var showTrueAlert = false
@State var showFalseAlert = false
var body: some View
Button(action:
let isTrue = Bool.random()
if isTrue
self.showTrueAlert = true
self.showAlert = true
print("True Alert")
else
self.showFalseAlert = true
self.showAlert = true
print("False Alert")
)
Text("Random Alert")
.font(.largeTitle)
.alert(isPresented: Binding<Bool>(
get:
self.showAlert
,
set:
self.showAlert = $0
self.showTrueAlert = false
self.showFalseAlert = false
))
if (showTrueAlert)
return Alert(title: Text("True"))
else
return Alert(title: Text("False"))
【讨论】:
以上是关于SwiftUI同一按钮的多个警报[重复]的主要内容,如果未能解决你的问题,请参考以下文章