深度编程 SwiftUI NavigationView 导航 [英] Deep programmatic SwiftUI NavigationView navigation

查看:96
本文介绍了深度编程 SwiftUI NavigationView 导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按顺序获得一个深层嵌套的程序化导航堆栈.当手动完成导航(即:按下链接)时,以下代码按预期工作.当您按下 Set Nav 按钮时,导航堆栈确实发生了变化 - 但不像预期的那样 - 并且您最终会得到一个损坏的堆栈 [start ->;b->bbb] 视图之间有很多翻转

I'm trying to get a deep nested programmatic navigation stack in order. The following code works as expected when navigation is done by hand (ie: pressing the links). When you press the Set Nav button the navigation stack does change - but not as expected - and you end up with a broken stack [start -> b -> bbb] with much flipping between views

class NavState: ObservableObject {
    @Published var firstLevel: String? = nil
    @Published var secondLevel: String? = nil
    @Published var thirdLevel: String? = nil
}

struct LandingPageView: View {

    @ObservedObject var navigationState: NavState

    func resetNav() {
        self.navigationState.firstLevel = "b"
        self.navigationState.secondLevel = "ba"
        self.navigationState.thirdLevel = "bbb"
    }

    var body: some View {

        return NavigationView {
            List {
                NavigationLink(
                    destination: Place(
                        text: "a",
                        childValues: [ ("aa", [ "aaa"]) ],
                        navigationState: self.navigationState
                    ).navigationBarTitle("a"),
                    tag: "a",
                    selection: self.$navigationState.firstLevel
                ) {
                    Text("a")
                }
                NavigationLink(
                    destination: Place(
                        text: "b",
                        childValues: [ ("bb", [ "bbb"]), ("ba", [ "baa", "bbb" ]) ],
                        navigationState: self.navigationState
                    ).navigationBarTitle("b"),
                    tag: "b",
                    selection: self.$navigationState.firstLevel
                ) {
                    Text("b")
                }

                Button(action: self.resetNav) {
                    Text("Set Nav")
                }
            }
            .navigationBarTitle("Start")
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}


struct Place: View {
    var text: String
    var childValues: [ (String, [String]) ]

    @ObservedObject var navigationState: NavState

    var body: some View {
        List(childValues, id: \.self.0) { childValue in
            NavigationLink(
                destination: NextPlace(
                    text: childValue.0,
                    childValues: childValue.1,
                    navigationState: self.navigationState
                ).navigationBarTitle(childValue.0),
                tag: childValue.0,
                selection: self.$navigationState.secondLevel
            ) {
                Text(childValue.0)
            }
        }
    }
}

struct NextPlace: View {
    var text: String
    var childValues: [String]

    @ObservedObject var navigationState: NavState

    var body: some View {
        List(childValues, id: \.self) { childValue in
            NavigationLink(
                destination: FinalPlace(
                    text: childValue,
                    navigationState: self.navigationState
                ).navigationBarTitle(childValue),
                tag: childValue,
                selection: self.$navigationState.thirdLevel
            ) {
                Text(childValue)
            }
        }
    }
}

struct FinalPlace: View {
    var text: String
    @ObservedObject var navigationState: NavState

    var body: some View {
        let concat: String = "\(navigationState.firstLevel)/\(navigationState.secondLevel))/\(navigationState.thirdLevel)/"

        return VStack {
            Text(text)
            Text(concat)
        }
    }
}

我最初尝试将导航过渡动画作为问题源来解决 - 但 如何禁用 NavigationView 推送和弹出动画 暗示这是不可配置的

I originally attempted to tackle navigation transition animations as a problem source - but How to disable NavigationView push and pop animations is suggesting that this is not configurable

是否有任何关于 >1 级程序化导航的合理示例?

Are there any sane examples of >1 level programmatic navigation working out there?

我希望在这里获得的部分内容也是用于导航正常工作的初始状态 - 如果我从具有我希望反映的导航状态的外部上下文进来(即:从带有一些应用内上下文的通知,或从保存到磁盘编码状态开始)然后我希望能够加载顶部 View 导航正确指向右子视图.本质上 - 用实际值替换 NavState 中的 nils.Qt 的 QML 和 ReactRouter 都可以声明性地做到这一点——SwiftUI 也应该能够做到.

Part of what I am looking to get here is also initial state for navigation working correctly - if I come in from an external context with a navigation state I wish to reflect (ie: from a notification with some in-app context to start from, or from a saved-to-disk-encoded-state) then I would expect to be able to load up the top View with navigation correctly pointing to the right child view. Essentially - replace the nils in the NavState with real values. Qt's QML and ReactRouter can both do this declaratively - SwiftUI should be able to as well.

推荐答案

将我自己的解决方案放在此处作为一个选项,以防有人遇到 NavigationView 似乎没有的导航要求能够实现.在我的书中 - 功能比图形元素和动画更难修复.灵感来自 https://medium.com/swlh/swiftui-custom-navigation-view-for-your-applications-7f6effa7dbcf

Putting my own solution up here as a option in the case that someone is hitting the same requirements for navigation that NavigationView does not seem to be able fulfill. In my book - functionality is a lot harder to fix than graphical elements and animation. Inspired by https://medium.com/swlh/swiftui-custom-navigation-view-for-your-applications-7f6effa7dbcf

它的工作原理是根级的单个声明变量决定导航堆栈 - 当从 a 链跳转到 b 等操作时,绑定到单个变量似乎很奇怪 需要在我上面演示中的链或从特定位置开始

It works off the idea of a single declarative variable at the root level determines the navigation stack - binding to individual variables seems odd when an operation like jumping from the a chain to the b chain in my above demo or starting at a particular position is required

我使用了像 URI 这样的字符串化路径的概念作为变量概念 - 这可能会被一个更具表现力的模型(如 enums 的向量)替换

I've used the concept of a stringified path like a URI as the variable concept - this could probably be replaced with a more expressive model (like a vector of enums)

重要的警告 - 它非常粗糙,没有动画,根本看起来不像原生,使用 AnyView,你不能多次使用相同的节点名称,只反映一个 StackNavigationViewStyle 等 - 如果我把它变成更漂亮、更理智和更通用的东西,我会把它放在 Gist 中.

Big ol caveats - its very rough, has no animations, doesn't look native at all, uses AnyView, you can't have the same node name more than once, only reflects a StackNavigationViewStyle, etc - if I make this into something more pretty, sane and generic I'll put that up in Gist.

struct NavigationElement {
    var tag: String
    var title: String
    var viewBuilder: () -> AnyView
}

class NavigationState: ObservableObject {
    let objectWillChange = ObservableObjectPublisher()

    var stackPath: [String] {
        willSet {
            if rectifyRootElement(path: newValue) {
                _stackPath = newValue
                rectifyStack(path: newValue, elements: _stackElements)
            }
        }
    }

    /// Temporary storage for the most current stack path during transition periods
    private var _stackPath: [String] = []

    @Published var stack: [NavigationElement] = []

    var stackElements: [String : NavigationElement] = [:] {
        willSet {
            _stackElements = newValue
            rectifyStack(path: _stackPath, elements: newValue)
        }
    }

    /// Temporary storage for the most current stack elements during transition periods
    private var _stackElements: [String : NavigationElement] = [:]

    init(initialPath: [String] = []) {
        self.stackPath = initialPath
        rectifyRootElement(path: initialPath)
        _stackPath = self.stackPath
    }

    @discardableResult func rectifyRootElement(path: [String]) -> Bool {
        // Rectify root state if set from outside
        if path.first != "" {
            stackPath = [ "" ] + path
            return false
        }
        return true
    }

    private func rectifyStack(path: [String], elements: [String : NavigationElement]) {
        var newStack: [NavigationElement] = []
        for tag in path {
            if let elem = elements[tag] {
                newStack.append(elem)
            }
            else {
                print("Path has a tag '\(tag)' which cannot be represented - truncating at last usable element")
                break
            }
        }
        stack = newStack
    }
}

struct NavigationStack<Content: View>: View {
    @ObservedObject var navState: NavigationState
    @State private var trigger: String = "humperdoo"    //HUMPERDOO! Chose something that would not conflict with empty root state - could probably do better with an enum

    init(_ navState: NavigationState, title: String, builder: @escaping () -> Content) {
        self.navState = navState
        self.navState.stackElements[""] = NavigationElement(tag: "", title: title, viewBuilder: { AnyView(builder()) })
    }

    var backButton: some View {
        Button(action: { self.navState.stackPath.removeLast() }) {
            Text("Back")
        }
    }

    var navigationHeader: some View {
        HStack {
            ViewBuilder.buildIf( navState.stack.count > 1 ? backButton : nil )
            Spacer()
            ViewBuilder.buildIf( navState.stack.last?.title != nil ? Text(navState.stack.last!.title) : nil )
            Spacer()
        }
        .frame(height: 40)
        .background(Color(.systemGray))
    }

    var currentNavElement: some View {
        return navState.stack.last!.viewBuilder()
    }

    var body: some View {
        VStack {
            // This is an effectively invisible element which primarily serves to force refreshes of the tree
            Text(trigger)
            .frame(width: 0, height: 0)
            .onReceive(navState.$stack, perform: { stack in
                self.trigger = stack.reduce("") { tag, elem in
                    return tag + "/" + elem.tag
                }
            })
            navigationHeader
            ViewBuilder.buildBlock(
                navState.stack.last != nil
                ? ViewBuilder.buildEither(first: currentNavElement)
                : ViewBuilder.buildEither(second: Text("The navigation stack is empty - this is odd"))
            )
        }
    }
}

struct NavigationDestination<Label: View, Destination: View>: View {

    @ObservedObject var navState: NavigationState
    var tag: String
    var label: () -> Label

    init(_ navState: NavigationState, tag: String, title: String, destination: @escaping () -> Destination, label: @escaping () -> Label) {
        self.navState = navState
        self.tag = tag
        self.label = label
        self.navState.stackElements[tag] = NavigationElement(tag: tag, title: title, viewBuilder: { AnyView(destination()) })
    }

    var body: some View {
        label()
        .onTapGesture {
            self.navState.stackPath.append(self.tag)
        }
    }
}

以及一些基本的使用代码

And some basic usage code

struct LandingPageView: View {

    @ObservedObject var navState: NavigationState

    var destinationA: some View {
        List {
            NavigationDestination(self.navState, tag: "aa", title: "AA", destination: { Text("AA") }) {
                Text("Go to AA")
            }
            NavigationDestination(self.navState, tag: "ab", title: "AB", destination: { Text("AB") }) {
                Text("Go to AB")
            }
        }
    }

    var destinationB: some View {
        List {
            NavigationDestination(self.navState, tag: "ba", title: "BA", destination: { Text("BA") }) {
                Text("Go to BA")
            }
            Button(action: { self.navState.stackPath = [ "a", "ab" ] }) {
                Text("Jump to AB")
            }
        }
    }

    var body: some View {
        NavigationStack(navState, title: "Start") {
            List {
                NavigationDestination(self.navState, tag: "a", title: "A", destination: { self.destinationA }) {
                    Text("Go to A")
                }
                NavigationDestination(self.navState, tag: "b", title: "B", destination: { self.destinationB }) {
                    Text("Go to B")
                }
            }
        }
    }
}

这篇关于深度编程 SwiftUI NavigationView 导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆