我正在尝试按顺序获取深层嵌套的程序化导航堆栈。手动完成导航(即:按下链接)后,以下代码将按预期工作。当您按下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)
}
}
}
我最初试图将导航过渡动画作为问题源,但是How to disable NavigationView push and pop animations表示这是不可配置的
这里有没有健全的> 1级程序化导航示例?
编辑:我想要到达这里的一部分也是初始状态,以使导航正常工作-如果我来自具有导航状态的外部环境,则希望反映(即:从通知(从某个应用内上下文开始或从保存到磁盘编码状态开始),那么我希望能够加载顶部View
,并正确指向正确的孩子导航视图。本质上-用实际值替换nil
中的NavState
。 Qt的QML和ReactRouter都可以声明性地做到这一点-SwiftUI也应该能够做到。
答案 0 :(得分: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"
}
}
}
答案 1 :(得分:0)
最简单的方法是删除后续级别的@Published。
class NavState: ObservableObject {
@Published var firstLevel: String? = nil
var secondLevel: String? = nil
var thirdLevel: String? = nil
}
这还告诉您如何有条件地更改变量可能会影响导航行为。
答案 2 :(得分:0)
如果有人遇到NavigationView
似乎无法满足的相同导航要求,请在此处提出自己的解决方案。在我的书中-功能比图形元素和动画要难得多。受https://medium.com/swlh/swiftui-custom-navigation-view-for-your-applications-7f6effa7dbcf
它从根本上解决了单个声明性变量的想法,即在根目录级别决定了导航堆栈-当像从a
链跳转到b
链这样的操作时,绑定到各个变量似乎很奇怪。我需要上面的演示或从特定位置开始
我将诸如URI之类的字符串化路径的概念用作变量概念-可以用更具表现力的模型(例如enum
s的向量)代替它
大提示:非常粗糙,没有动画,根本看起来不是原生的,使用AnyView
,您不能多次使用相同的节点名称,只能反映一个{{1} }等-如果我将其转换为更漂亮,理智和通用的名称,我会在Gist中提出。
StackNavigationViewStyle
一些基本用法代码
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)
}
}
}