gpt4 book ai didi

ios - SwiftUI 组合 : TabView is not updating on selection when property stored in different viewmodel

转载 作者:行者123 更新时间:2023-12-05 05:41:10 27 4
gpt4 key购买 nike

我正在开发具有页面样式Tabview,我想在按钮操作上滚动tabview。按钮添加到 NavigationMenu 中。

NavigationMenu viewNavigationModel(ViewModel) 与父级分离。

选择处理在 NavigationModel 中完成。

在标签页滑动时,我可以看到 NavigationMenu 的变化,这很好。

但是如果我点击按钮,tabview 页面不会滑动。即使我在方法 onReceive 上收到更改事件。

代码:

import SwiftUI
import Combine

final class NavigationModel: ObservableObject {
@Published var selectedItem = ""
@Published var items: [String] = [
"Button 1", "Button 2", "Button 3"
]
}

struct NavigationMenu: View {

@ObservedObject var viewModel: NavigationModel

var body: some View {
HStack {
ForEach(0..<3, id: \.self) { index in
let title = viewModel.items[index]
Button {
viewModel.selectedItem = title
} label: {
Text(title)
.font(.system(.body))
.padding()
.foregroundColor(
viewModel.selectedItem == title ? .white : .black
)
.background(viewModel.selectedItem == title ? .black : .yellow)
}
}
}
}
}

final class TabViewModel: ObservableObject {
var navModel = NavigationModel()
}

struct TabviewWithMenuView: View {

@ObservedObject var viewModel = TabViewModel()

var body: some View {
parentView
}

private var parentView: some View {
VStack(spacing: 0) {
Spacer()
NavigationMenu(viewModel: viewModel.navModel)
pageView
}
.onReceive(viewModel.navModel.$selectedItem) { output in
print("Button tapped:", output)
}
}

private var pageView: some View {
TabView(selection: $viewModel.navModel.selectedItem) {
ForEach(0..<3, id: \.self) { index in
let tag = viewModel.navModel.items[index]
item(tag: tag)
.tag(tag)
}
}
.tabViewStyle(.page(indexDisplayMode: .never))
.transition(.slide)
}

private func item(tag: String) -> some View {
VStack {
Text("PAGE: " + tag)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.red)
}

}

图片:

最佳答案

ObservableObject内部的ObservableObject没有被观察到,我们需要显式观察被改变的实例。

在这种情况下,一个可能的解决方案是分离 PageView 并向其注入(inject)导航 View 模型,以便对其进行观察。

使用 Xcode 13.3/iOS 15.4 测试

demo

这是主要部分:


NavigationMenu(viewModel: viewModel.navModel)
PageView(navModel: viewModel.navModel)

...

struct PageView: View {
@ObservedObject var navModel: NavigationModel

var body: some View {
pageView
}
// ....
}

Test module in project is here

关于ios - SwiftUI 组合 : TabView is not updating on selection when property stored in different viewmodel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72313228/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com