大多数显示示例是Alert
指某种@State
被用作控制警报视图的呈现/隐藏状态的绑定。
例如showingAlert
(来源):
struct ContentView : View {
@State 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!"))
)
}
}
}
当从 UI 层触发警报时,这是一个很好的解决方案 - 如示例所示:
Button(action: {
self.showingAlert = true
}
但是如果我们想用特定的消息从控制器/视图模型层触发它呢?例如,我们进行网络调用 -URLSession
可以Publisher
发送Data
或Error
我们想要作为消息推送给用户的Alert
.
@State
被设计为从视图中管理body
,所以在这种情况下我们似乎应该使用 an @ObjectBinding
。看来我们也需要一些message
,所以可以在下面引用body
:
Alert(
title: Text("Important message"),
message: Text(objectBinding.message)
)
在这里showingAlert
会有点多余,因为我们可以定义message
为String?
并创建一个绑定presentation
:
Binding<Bool>(
getValue: { objectBinding.message != nil },
setValue: { if !$0 { objectBinding.message = nil } }
)
这是一种可行的方法并且有效,但有两件事让我有点焦虑:
message
由两个抽象管理的事实- 警报的显示/隐藏状态的信息和管理泄漏到控制器/视图模型/对象绑定中。最好将呈现/隐藏状态私下保留在视图中。
- 事实上,消息一直保存在控制器/视图模型/对象绑定中,直到它被视图(绑定)“消耗”。
可以做得更好吗?