ios - 如果未显示所有 NavigationLink,则 NavigationView 中 SwiftUI 的 NavigationLink `tag` 和 `selection` 将停止工作

标签 ios swiftui swiftui-navigationlink swiftui-navigationview

我有一个 Form 中的项目列表在 NavigationView , 每个都有一个可以通过 NavigationLink 访问的详细 View .
当我向列表中添加一个新元素时,我想显示它的详细 View 。为此,我使用 @State var currentSelectionNavigationLink接收为 selection ,并且每个元素的功能为 tag :

NavigationLink(
  destination: DetailView(entry: entry),
  tag: entry,
  selection: $currentSelection,
  label: { Text("The number \(entry)") })
这有效,它遵循 Apple docsbest practises .
令人惊讶的是,它 当列表的元素多于屏幕(加上〜2)时工作。问:为什么?我该如何解决它?

我做了一个最小的例子来复制行为:
import SwiftUI

struct ContentView: View {
    @State var entries = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
    @State var currentSelection: Int? = nil

    var body: some View {
        NavigationView {
            Form {
                ForEach(entries.sorted(), id: \.self) { entry in
                    NavigationLink(
                        destination: DetailView(entry: entry),
                        tag: entry,
                        selection: $currentSelection,
                        label: { Text("The number \(entry)") })
                }
            }
            .toolbar {
                ToolbarItem(placement: ToolbarItemPlacement.navigationBarLeading) { Button("Add low") {
                    let newEntry = (entries.min() ?? 1) - 1
                    entries.insert(newEntry, at: 1)
                    currentSelection = newEntry
                } }
                ToolbarItem(placement: ToolbarItemPlacement.navigationBarTrailing) { Button("Add high") {
                    let newEntry = (entries.max() ?? 50) + 1
                    entries.append(newEntry)
                    currentSelection = newEntry
                } }
                ToolbarItem(placement: ToolbarItemPlacement.bottomBar) {
                    Text("The current selection is \(String(describing: currentSelection))")
                }
            }
        }
    }
}

struct DetailView: View {
    let entry: Int
    var body: some View {
        Text("It's a \(entry)!")
    }
}
(我通过将列表减少到 5 项并在标签上设置填充来排除元素数量是核心问题:label: { Text("The number \(entry).padding(30)") }))
正如您在屏幕记录中看到的那样,在达到临界数量的元素后(通过预先或附加到列表),底部工作表仍然显示 currentSelection正在更新,但没有导航发生。
我使用了 iOS 14.7.1、Xcode 12.5.1 和 Swift 5。
adding to the start of the list
adding to the end of the list

最佳答案

发生这种情况是因为没有渲染较低的项目,所以在层次结构中没有 NavigationLink有这样的标签
我建议您使用 ZStack + EmptyView NavigationLink “黑客”。
我也在这里使用 LazyView,感谢 @autoclosure它让我通过包装 currentSelection : 这只会在 NavigationLink 时调用处于事件状态,这发生在 currentSelection != nil

struct ContentView: View {
    @State var entries = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
    @State var currentSelection: Int? = nil

    var body: some View {
        NavigationView {
            ZStack {
                EmptyNavigationLink(
                    destination: { DetailView(entry: $0) },
                    selection: $currentSelection
                )
                Form {
                    ForEach(entries.sorted(), id: \.self) { entry in
                        NavigationLink(
                            destination: DetailView(entry: entry),
                            label: { Text("The number \(entry)") })
                    }
                }
                .toolbar {
                    ToolbarItem(placement: ToolbarItemPlacement.navigationBarLeading) { Button("Add low") {
                        let newEntry = (entries.min() ?? 1) - 1
                        entries.insert(newEntry, at: 1)
                        currentSelection = newEntry
                    } }
                    ToolbarItem(placement: ToolbarItemPlacement.navigationBarTrailing) { Button("Add high") {
                        let newEntry = (entries.max() ?? 50) + 1
                        entries.append(newEntry)
                        currentSelection = newEntry
                    } }
                    ToolbarItem(placement: ToolbarItemPlacement.bottomBar) {
                        Text("The current selection is \(String(describing: currentSelection))")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    let entry: Int
    var body: some View {
        Text("It's a \(entry)!")
    }
}

public struct LazyView<Content: View>: View {
    private let build: () -> Content
    public init(_ build: @autoclosure @escaping () -> Content) {
        self.build = build
    }
    public var body: Content {
        build()
    }
}

struct EmptyNavigationLink<Destination: View>: View {
    let lazyDestination: LazyView<Destination>
    let isActive: Binding<Bool>
    
    init<T>(
        @ViewBuilder destination: @escaping (T) -> Destination,
        selection: Binding<T?>
    )  {
        lazyDestination = LazyView(destination(selection.wrappedValue!))
        isActive = .init(
            get: { selection.wrappedValue != nil },
            set: { isActive in
                if !isActive {
                    selection.wrappedValue = nil
                }
            }
        )
    }
    
    var body: some View {
        NavigationLink(
            destination: lazyDestination,
            isActive: isActive,
            label: { EmptyView() }
        )
    }
}
查看更多关于 LazyView 的信息, 它通常对 NavigationLink 有帮助:在真正的应用程序中,目的地可能是一个巨大的屏幕,当你有一个 NavigationLink在每个单元格中,SwiftUI 将处理所有可能导致滞后的单元格

关于ios - 如果未显示所有 NavigationLink,则 NavigationView 中 SwiftUI 的 NavigationLink `tag` 和 `selection` 将停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68783396/

相关文章:

slider - 当用户用 swiftUI 放下 slider 时如何调用函数?

SwiftUI 在详细 View 中覆盖导航栏外观

php - NSArray 无法识别我放入其中的内容并给我错误

ios - Xcode 6 与 Swift 超慢打字和自动完成

ios - UIButton 上奇怪的 CAGradientLayer 错误

android - 从 App Store 和 Google Play 将每个移动应用程序下载到 Mac 或 PC 的最快/最简单方法是什么?

ios - 如何与代码并排打开 SwiftUI 预览?

ios - 向 TextEditor 添加水平填充,但防止它因此在内部移动滚动条

swiftui - 从 SwiftUI 打开 UIKit ViewController 的最佳方式是什么

ios - 在 SwiftUI 中使用 List 时如何使用 NavigationLink isActive 绑定(bind)?