8

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

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 推送和弹出动画表明这是不可配置的

那里有 > 1 级程序化导航的合理示例吗?

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

4

3 回答 3

0

最简单的方法是删除后续级别的@Published。

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

这也告诉您如何有条件地更改变量可能会影响导航行为。

于 2019-12-19T16:03:43.370 回答
0

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

它解决了根级别的单个声明性变量确定导航堆栈的想法 - 当需要像我上面的演示中从a链跳转到b链或从特定位置开始这样的操作时,绑定到单个变量似乎很奇怪

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

大的警告 - 它非常粗糙,没有动画,看起来根本不是原生的,使用AnyView,你不能多次拥有相同的节点名称,只反映 a StackNavigationViewStyle,等等 - 如果我把它变成更漂亮的东西,理智和通用我会把它放在 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)
        }
    }
}

以及一些基本的使用代码

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")
                }
            }
        }
    }
}
于 2019-12-20T00:48:44.910 回答
0

这是因为动画完成时会形成新的堆栈级别,这就是它在手动点击的情况下起作用的原因。

通过以下修改,它可以工作:

func resetNav() {
    self.navigationState.firstLevel = "b"
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        self.navigationState.secondLevel = "ba"
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.navigationState.thirdLevel = "bbb"
        }
    }
}
于 2019-12-19T07:10:55.987 回答