SwiftUI NavigationLink无需单击即可立即加载目标视图 [英] SwiftUI NavigationLink loads destination view immediately, without clicking

查看:187
本文介绍了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?

推荐答案

我发现解决此问题的最佳方法是使用惰性视图.

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无需单击即可立即加载目标视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆