SwiftUI NavigationLink 自行弹出 [英] SwiftUI NavigationLink pops out by itself

查看:34
本文介绍了SwiftUI NavigationLink 自行弹出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的用例,其中一个屏幕使用 NavigationLink 推送另一个屏幕.iOS 14.5 beta (1, 2, 3) 有一个奇怪的行为,推送的屏幕刚被推送就弹出.

I have a simple use case where a screen pushes another screen using the NavigationLink. There is a strange behaviour iOS 14.5 beta (1, 2, 3), where the pushed screen is popped just after being pushed.

我设法创建了一个示例应用程序并在其中重现它.我相信原因是 @Environment(\.presentationMode) 的存在似乎重新创建了视图并导致推送的视图被弹出.

I manage to create a sample app where I reproduce it. I believe the cause is the presence of @Environment(\.presentationMode) that seem to re-create the view and it causes the pushed view to be popped.

完全相同的 cod 在 Xcode 12/iOS 14.4 中运行良好

The exact same cod works fine in Xcode 12 / iOS 14.4

这是一个示例代码.

import SwiftUI

public struct FirstScreen: View {
    public init() {}
    public var body: some View {
        NavigationView {
            List {
                row
                row
                row
            }
        }
    }
    private var row: some View {
        NavigationLink(destination: SecondScreen()) {
            Text("Row")
        }
    }
}

struct SecondScreen: View {

    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

    public var body: some View {
        VStack(spacing: 10) {
            NavigationLink(destination: thirdScreenA) {
                Text("Link to Third Screen A")
            }

            NavigationLink(destination: thirdScreenB) {
                Text("Link to Third Screen B")
            }

            Button("Go back", action: { presentationMode.wrappedValue.dismiss() })
        }

    }

    var thirdScreenA: some View {
        Text("thirdScreenA")
    }

    var thirdScreenB: some View {
        Text("thirdScreenB")
    }
}


struct FirstScreen_Previews: PreviewProvider {
    static var previews: some View {
        FirstScreen()
    }
}

推荐答案

当正好有 2 个 NavigationLinks 时,这看起来像是一个错误.如果您添加另一个空链接,它就会消失:

Looks like a bug when there is exactly 2 NavigationLinks. If you add another empty link it goes away:

NavigationLink(destination: EmptyView(), label: {})

更多详情:https://forums.swift.org/t/14-5-beta3-navigationlink-unexpected-pop/45279

这篇关于SwiftUI NavigationLink 自行弹出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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