本文介绍了SwiftUI NavigationLink 立即加载目标视图,无需单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码:

struct HomeView: View {
    var body: some View {
        NavigationView {
            List(dataTypes) { dataType in
                NavigationLink(destination: AnotherView()) {
                    HomeViewRow(dataType: dataType)
                }
            }
        }
    }
}

奇怪的是,当HomeView 出现时,NavigationLink 立即加载AnotherView.结果,所有 AnotherView 依赖项也被加载,即使它在屏幕上还不可见.用户必须单击该行才能使其出现.我的 AnotherView 包含一个 DataSource,在那里发生各种事情.问题是此时加载了整个 DataSource,包括一些计时器等.

What's weird, when HomeView appears, NavigationLink immediately loads the AnotherView. As a result, all AnotherView dependencies are loaded as well, even though it's not visible on the screen yet. The user has to click on the row to make it appear.My AnotherView contains a DataSource, where various things happen. The issue is that whole DataSource is loaded at this point, including some timers etc.

我做错了什么..?如何以这种方式处理它,一旦用户按下 HomeViewRow 就会加载 AnotherView?

Am I doing something wrong..? How to handle it in such way, that AnotherView gets loaded once the user presses on that HomeViewRow?

推荐答案

我发现解决此问题的最佳方法是使用 Lazy View.

The best way I have found to combat this issue is by using a Lazy View.

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

那么 NavigationLink 将如下所示.您可以将要显示的视图放在 ()

Then the NavigationLink would look like this. You would place the View you want to be displayed inside ()

NavigationLink(destination: NavigationLazyView(DetailView(data: DataModel))) { Text("Item") }

这篇关于SwiftUI NavigationLink 立即加载目标视图,无需单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 14:03