jsoneaday
(Jsoneaday)
1
I have an @EnvironmentObject, store, that has a variable I need to pass the variable as a parameter to my @StateObject, vm, initializer. I first tried the init but an @EnvironmentObject is not yet existing upon View init. So then I tried the onAppear but onAppear does not allow use of self. Is this even possible? For reference I've included both the init and the onAppear, neither works.
struct NewsView: View {
@EnvironmentObject var store: Store
@StateObject private var vm: NewsViewModel
init() {
self._vm = StateObject(wrappedValue: NewsViewModel(self._store.wrappedValue.newsApi))
}
var body: some View {
if vm.show == true {
HStack {
Image("round-flag")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20)
.rotationEffect(.degrees(-28))
Text(self.vm.news?.subject ?? "")
.instaStylePrimary()
Button {
vm.show = false
} label: {
Image(systemName: "xmark")
.instaStylePrimary()
.frame(width: 12)
.foregroundColor(.gray)
}
}
.onChange(of: self.store) { newStore in
self._vm = StateObject(wrappedValue: NewsViewModel(newStore.newsApi))
}
}
}
}
Lantua
2
Question specific to SwiftUI, which is Apple's specific framework, is off-topic for this forum. I'd suggest that you ask this kind of questions over Apple Developer Forums instead. You're more likely to get a help there.