代码之家  ›  专栏  ›  技术社区  ›  elight

SwiftUI选项卡视图索引视图不考虑页面视图索引

  •  0
  • elight  · 技术社区  · 5 年前

    我的目标是将当前TabView索引的真实来源保持在app state中。但我并没有看到SwiftUI TabView索引指示器的预期行为。

    我能做的是有两种结果中的一种:让绑定正确地更新真相的来源,或者让指标按预期工作。我似乎不能两者兼得。

    我已经将代码精简到下面的测试用例中。我希望TabView索引视图(指示器)更新并显示当前视图在TabView内容数组中的索引位置(当然,相对而言,so+1)。

    结果是索引根本不更新。在原始代码中 滞后 一个。。

    有经验的人能提供一些建议或指出我哪里出了问题吗?

    import SwiftUI
    
    class Item: Identifiable {
        let id = Int.random(in: 0..<1000)
    }
    
    class SourceOfTruth: ObservableObject {
        @Published var items: [Item] = [Item(), Item(), Item()]
        /// Source of truth for app state
        var _selectedItem: Int? {
            willSet {
                print("\(newValue ?? 0)")
            }
        }
        /// Exposed SwiftUI binding
        public lazy var selectedItem: Binding<Int> = Binding<Int>(get: {
            self._selectedItem ?? -1
        }, set: {
            self._selectedItem = $0
        })
    
        init () {
            _selectedItem = items.first?.id
        }
    }
    
    struct BindingTestView: View {
        @EnvironmentObject var appState: SourceOfTruth
    
        var body: some View {
            if appState.items.count > 0 {
                TabView(selection: appState.selectedItem) {
                    ForEach(appState.items) { item in
                        Text("\(item.id)")
                                .tag(item.id)
                    }
                }
                        .tabViewStyle(PageTabViewStyle(indexDisplayMode: .always))
                        .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
            } else {
                Text("No items")
            }
        }
    }
    
    @main
    struct SwiftUICombineTestingApp: App {
        let appState = SourceOfTruth()
    
        var body: some Scene {
            WindowGroup {
                BindingTestView().environmentObject(appState)
            }
        }
    }
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   pawello2222    5 年前

    你需要补充 @Published 因此,可以通过视图观察变量:

    @Published var _selectedItem: Int? {
        willSet {
            print("\(newValue ?? 0)")
        }
    }