使用 MVVM 在 SwiftUI 中显示警报

编程入门 行业动态 更新时间:2024-10-27 10:24:50
本文介绍了使用 MVVM 在 SwiftUI 中显示警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用 SwiftUI 和 MVVM 架构构建应用程序.我想让我的视图在它的 ViewModel 认为有必要的时候显示一个警报——比如,当它有一个来自模型的新结果时.因此,假设每当 VM 检测到新结果时,它都会相应地设置其 status:

I'm trying to build an app using SwiftUI and an MVVM architecture. I'd like to have my View present an alert whenever its ViewModel deems it necessary—say, when it has a new result of some sort available from the Model. So suppose whenever the VM detects a new result it sets its status accordingly:

视图模型:

enum Status { case idle case computing case newResultAvailable } class MyViewModel: ObservableObject { @Published var status = Status.idle ... }

视图:

struct ContentView: View { @ObservedObject var vm = MyViewModel() @State private var announcingResult = false { didSet { // reset VM status when alert is dismissed if announcingResult == false { vm.status = .idle } } } var body: some View { Text("Hello") .alert(isPresented: $announcingResult) { Alert(title: Text("There's a new result!"), message: nil, dismissButton: .default(Text("OK"))) } } }

Apple 设计了 ​​.alert() 修饰符以将绑定作为其第一个参数,以便在绑定属性变为 true 时显示警报.然后,当警报解除时,绑定属性会自动设置为 false.

Apple has designed the .alert() modifier to take a binding as its first argument, so that the alert is displayed whenever the bound property becomes true. Then, when the alert is dismissed, the bound property is automatically set to false.

我的问题是:当 VM 的 status 变为 .newResultAvailable 时,我如何让警报出现?在我看来,这就是 MVVM 应该如何正确运行,这与所有 SwiftUI WWDC 演示的精神非常相似,但我找不到方法......

My question is: How can I have the alert appear whenever the VM's status becomes .newResultAvailable? It seems to me that that's how proper MVVM should function, and it feels very much in the spirit of all the SwiftUI WWDC demos, but I can't find a way…

推荐答案

这里是可能的方法(已测试并适用于 Xcode 11.3+)

Here is possible approach (tested & works with Xcode 11.3+)

struct ContentView: View { @ObservedObject var vm = MyViewModel() var body: some View { let announcingResult = Binding<Bool>( get: { self.vm.status == .newResultAvailable }, set: { _ in self.vm.status = .idle } ) return Text("Hello") .alert(isPresented: announcingResult) { Alert(title: Text("There's a new result!"), message: nil, dismissButton: .default(Text("OK"))) } } }

有时以下符号可能更可取

also sometimes the following notation can be preferable

var body: some View { Text("Hello") .alert(isPresented: Binding<Bool>( get: { self.vm.status == .newResultAvailable }, set: { _ in self.vm.status = .idle } )) { Alert(title: Text("There's a new result!"), message: nil, dismissButton: .default(Text("OK"))) } }

更多推荐

使用 MVVM 在 SwiftUI 中显示警报

本文发布于:2023-11-27 16:51:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638820.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:警报   MVVM   SwiftUI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!