@StateObject on iOS 13



我们今天意识到我们的应用针对iOS 14,并将其更改为iOS 13。我们发现我们无法在iOS 13上使用StateObject,并且出现了一些问题。这是我们得到的:

AlertState.swift

final class CardState: ObservableObject {
static let shared = CardState()
@Published var shouldShowCard = false

private init() {}

// Some other methods and variables
}

然后,我们这样使用它:

ContentView.swift

struct ContentView: View {
@StateObject var cardState = CardState.shared

var body: some View {
ZStack(alignment: .center) {
if cardState.shouldShowCard {
Card()
}
}
}
}

Card.swift

struct Card: View {
@StateObject var cardState = CardState.shared
var body: some View {
// View
}
}

AlertState保存了更多的数据,比如我们在卡片中显示的文本。该卡可以从应用程序的任何屏幕触发。

所以,我们针对iOS 13并将StateObject替换为ObservedObject,但是当将shouldShowCard切换到false时,当卡被隐藏时,它停止了动画,视图就消失了。在使用StateObject时,我们应该使用什么来实现我们曾经拥有的功能?我们有点迷路了,找到的都试过了。

提前感谢。

这是一个可能的解决方案。我们将ObservedObjects@State包装在一个视图中。

struct ViewModelWrapper<V: View, ViewModel: ObservableObject>: View {
private let contentView: V
@State private var contentViewModel: ViewModel
init(contentView: @autoclosure () -> V, vm: @autoclosure () -> ViewModel) {
self._contentViewModel = State(initialValue: vm())
self.contentView = contentView()
}
var body: some View {
contentView
.environmentObject(contentViewModel)
}
}

@State保留了模型对象,而.environmentObject允许每次视图重新渲染时传递完全相同的模型。

最新更新