swiftui视图开关语句导致tabview重置
我在swiftui视图中使用开关语句:
struct OnOffSwitchView: View {
@ObservedObject var vm = ViewModel()
var body: some View {
switch vm.state {
case .on:
OnView(vm: vm)
case .off:
OffView(vm: vm)
}
}
}
@MainActor class ViewModel: ObservableObject {
@Published var state: State = .on
enum State {
case on
case off
}
}
在儿童视图上更改viewModel状态(打开和关闭的状态相同),以便开关条件更新,呈现新视图:
struct OnView: View {
@ObservedObject var vm: ViewModel
var body: some View {
VStack {
Text("Welcome to On")
Button { vm.state = .off }
label: { Text("Toggle") }
}
}
}
这在单个视图中正常工作:
但是,当嵌套在选项卡视图中时,更改状态会导致TabView更改选项卡:
TabView {
Text("Home Tab")
.tabItem {
Image(systemName: "house.fill")
Text("Home")
}
OnOffSwitchView()
.tabItem {
Image(systemName: "switch.2")
Text("Switch")
}
}
有什么想法为什么会发生这种情况?我不确定(1)我的设置是否存在问题(管理状态更改),(2)我在TabView中缺少某些内容,或者(3)这是SwiftUI的问题。
I am using a switch statement in a SwiftUI view:
struct OnOffSwitchView: View {
@ObservedObject var vm = ViewModel()
var body: some View {
switch vm.state {
case .on:
OnView(vm: vm)
case .off:
OffView(vm: vm)
}
}
}
@MainActor class ViewModel: ObservableObject {
@Published var state: State = .on
enum State {
case on
case off
}
}
Where the child views are changing the ViewModel state (on and off are the same) such that the switch condition updates, rendering a new view:
struct OnView: View {
@ObservedObject var vm: ViewModel
var body: some View {
VStack {
Text("Welcome to On")
Button { vm.state = .off }
label: { Text("Toggle") }
}
}
}
This works fine in a single view:
But, when nesting in a tab view, changing the state causes the TabView to change tabs:
TabView {
Text("Home Tab")
.tabItem {
Image(systemName: "house.fill")
Text("Home")
}
OnOffSwitchView()
.tabItem {
Image(systemName: "switch.2")
Text("Switch")
}
}
Any ideas why this happening? I am unsure if (1) there is a problem with my setup (managing the state change), (2) I am missing something in the TabView, or (3) it's an issue with SwiftUI.
This toy example is available on GitHub Updated with answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这是一个错误,因为
OnoffSwitchView
应被检测到相同的(默认情况下基于属性的惯例)...无论如何,explicit选择
解决了用Xcode 13.4// iOS 15.5
*注意:在这种情况下,我建议使用
statebject
onfoffswitchview
中的视图模型。I think it is a bug, because
OnOffSwitchView
should be detected identical (by default properties-based convention)... anyway introducing explicitselection
solves the issueTested with Xcode 13.4 / iOS 15.5
*Note: I would recommend in this case use
StateObject
for view model inOnOffSwitchView
.