因此,我想我找到了一种方法,使SwiftUI中的导航变得灵活和松散耦合,但仍然是基于状态的,并且在某种程度上没有命令式导航错误(双推等)。
基本思想是有一个链接的视图列表(擦除到AnyView)和一个带有NavigationLink的递归视图,当列表中存在相应的视图时,该视图是活动的。
但它不起作用,我也不明白为什么。在iOS设备上,它只按一个级别深度,即使列表有多个层次深度,并且绑定返回true。
是SwiftUI错误还是我漏掉了什么?
struct ContentView: View {
@State
var navigationList: NavigationList?
var body: some View {
NavigationView {
Navigatable(list: $navigationList) {
Button("Push test", action: {
navigationList = .init(next: nil, screen: Screen {
TestView()
})
})
}
}
}
}
struct TestView: View {
@Environment(\.navigationList)
@Binding
var list
var body: some View {
Button("Push me", action: {
list = .init(next: nil, screen: Screen {
TestView()
})
})
}
}
struct Navigatable<Content: View>: View {
@Binding
var list: NavigationList?
let content: () -> Content
init(list: Binding<NavigationList?>, @ViewBuilder content: @escaping () -> Content) {
self._list = list
self.content = content
}
var body: some View {
ZStack {
NavigationLink(
isActive: isActive,
destination: {
Navigatable<Screen?>(list: childBinding) {
list?.screen
}
},
label: EmptyView.init
).hidden()
LazyView {
content()
}.environment(\.navigationList, $list)
}
}
var isActive: Binding<Bool> {
.init(
get: { list != nil },
set: {
if !$0 {
list = nil
}
}
)
}
var childBinding: Binding<NavigationList?> {
.init(
get: { list?.next },
set: { list?.next = $0 }
)
}
}
struct Screen: View {
let content: () -> AnyView
init<C: View>(@ViewBuilder content: @escaping () -> C) {
self.content = {
.init(content())
}
}
var body: some View {
content()
}
}
struct NavigationList {
@Indirect
var next: NavigationList?
let screen: Screen
}
enum NavigationListKey: EnvironmentKey {
static var defaultValue: Binding<NavigationList?> {
.constant(nil)
}
}
extension EnvironmentValues {
var navigationList: Binding<NavigationList?> {
get { self[NavigationListKey.self] }
set { self[NavigationListKey.self] = newValue }
}
}
struct LazyView<Content: View>: View {
@ViewBuilder var content: () -> Content
var body: some View {
content()
}
}
@propertyWrapper
struct Indirect<Wrapped> {
private final class Storage: CustomReflectable {
var wrapped: Wrapped
init(_ wrapped: Wrapped) {
self.wrapped = wrapped
}
var customMirror: Mirror {
.init(self, children: [(label: "wrapped", value: wrapped)])
}
}
private let storage: Storage
var wrappedValue: Wrapped {
get { storage.wrapped }
mutating set { storage.wrapped = newValue }
}
init(wrappedValue: Wrapped) {
self.storage = .init(wrappedValue)
}
}
发布于 2021-12-26 01:41:18
您缺少了isDetailLink(false)
,它允许将多个屏幕推送到一个导航控制器上。
但是,代码也存在结构性问题。最好使用设计好的SwiftUI视图数据结构,并让它们存储数据的等级。如果你使用自己的架构,那么你就失去了失效和扩散的魔力,它可能也会慢下来。
https://stackoverflow.com/questions/70481665
复制相似问题