0

我正在尝试构建一个分页应用程序,其中每个页面都有自己的 NavigationView。它有点工作,但我在导航栏中得到一个完全多余的“返回”按钮。到目前为止我的代码是 -

    struct AllListsView: View {
        
        @ObservedObject var viewModel: AllListsViewModel
        
        @State private var pageName: String = ""
        
        
        init(viewModel: AllListsViewModel) {
            self.viewModel = viewModel
        }
        
        var body: some View {
            
            IfLet($viewModel.listViews) { listViews in
                TabView {
                    ForEach(listViews) { $0 }
                }
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .automatic))
            } else: {
                Text("No lists")
            }
        }
    }

    struct ListView: View, Identifiable, Hashable {
        
        let id: String
        
        private var viewModel: ListViewModel
        
        init(viewModel: ListViewModel) {
            self.id = String(viewModel.list.index)
            self.viewModel = viewModel
        }
        
        var body: some View {
                
            NavigationView {
                Text("Any Text") // if I don't have this, nothing is displayed
                List(viewModel.listItems) {
                    Text("\($0.quantity) \($0.name)")
                }
                .navigationBarTitle(viewModel.list.name)
            }
        }
        
        func hash(into hasher: inout Hasher) {
            hasher.combine(id)
        }
        
        static func == (lhs: ListView, rhs: ListView) -> Bool {
            lhs.id == rhs.id
        }
    }

虚假返回按钮

但是,如果我将 NavigationView 放在 TabView 之外,它会正确显示,但是滚动列表不会缩小大标题文本,我必须在页面更改时更新 navigationBar 标题 -

    // AllListsView -
    var body: some View {
            
        IfLet($viewModel.listViews) { listViews in
                
            NavigationView {
                TabView {
                    ForEach(listViews, id: \.self) { listView in
                        listView
                            .onAppear {
                                pageName = listView.name
                            }
                    }
                }
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .automatic))
                .navigationBarTitle(pageName)
            }
                
        } else: {
            Text("No lists")
        }
    }

    // ListView -
    var body: some View {
                
        List(viewModel.listItems) {
            Text("\($0.quantity) \($0.name)")
        }
    }

正确的外表,错误的行为

我希望能够在 SwiftUI 中做到这一点,因为它看起来像是前进的道路。但我知道使用 UIKit 来做这件事对我来说是相当微不足道的,所以这很令人沮丧。

非常感谢任何帮助!

4

0 回答 0