本文介绍了SwiftUI 绑定到父视图重新渲染子视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个子视图,它从父视图获得了一个绑定,它控制着应用程序的侧边栏菜单.当我单击按钮切换 showSidebar 并打开菜单时,我的 vm 被重新创建,因为视图被重新渲染?有没有办法在不影响视图模型的情况下做到这一点?
struct OnboardingView:查看{@Environment (\.presentationMode) varpresentationMode@ObservedObject 私有变量 vm: OnboardingViewModel@State 私有变量过滤 = false@Binding var showSidebar: Boolinit(showSidebar: Binding) {self._showSidebar = showSidebarself.vm = OnboardingViewModel()}
解决方案
试试这个...
改变这个
@ObservedObject 私有变量 vm: OnboardingViewModel
到
@StateObject private var vm: OnboardingViewModel = OnboardingViewModel()
并摆脱
init(showSidebar: Binding) {self._showSidebar = showSidebarself.vm = OnboardingViewModel()}
在没有@StateObject 的视图中创建观察对象是不安全的
https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app
I have a child view that is given a binding from the parent view, which controls the app's sidebar menu. When I click the button to toggle showSidebar and open the menu, my vm is re-created because the view is re-rendered? Is there a way to do this without affecting the view model?
struct OnboardingView: View {
@Environment (\.presentationMode) var presentationMode
@ObservedObject private var vm: OnboardingViewModel
@State private var filtering = false
@Binding var showSidebar: Bool
init(showSidebar: Binding<Bool>) {
self._showSidebar = showSidebar
self.vm = OnboardingViewModel()
}
解决方案
Give this a try...
Change this
@ObservedObject private var vm: OnboardingViewModel
to
@StateObject private var vm: OnboardingViewModel = OnboardingViewModel()
and get rid of
init(showSidebar: Binding<Bool>) {
self._showSidebar = showSidebar
self.vm = OnboardingViewModel()
}
https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app
这篇关于SwiftUI 绑定到父视图重新渲染子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!