本文介绍了如何以编程方式触发NavigationLink出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以编程方式在出现时触发NavigationLink,但在所有情况下,出现(iOS 13.3.1,Xcode 11.3.1)后,目标视图都会立即弹出.

I am trying to trigger a NavigationLink programmatically on appear but in all cases the destination view pops immediately after appearing (iOS 13.3.1, Xcode 11.3.1).

设置如下:ContentView有一个到DetailView1的NavigationLink,而后者又有一个到DetailView2的NavigationLink.我希望在DetailView1首次加载时自动触发DetailView1中的NavigationLink(在我的实际代码中,这将基于条件,但这与此处无关).

The setup is as follows: ContentView has a NavigationLink to DetailView1 which in turn has a NavigationLink to DetailView2. I would like the NavigationLink in DetailView1 to be triggered automatically when the DetailView1 first loads (in my actual code this would be based on a condition, but this is irrelevant here).

这是基本代码(没有自动行为):

This is the basic code (without automatic behaviour):

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: DetailView1()) {
                Text("Open Detail View 1")
            }
                .navigationBarTitle(Text("ContentView"))
        }
    }
}

struct DetailView1: View {
@State private var isActive = false

    var body: some View {
        VStack {
            NavigationLink(destination: DetailView2(), isActive: $isActive) {
                EmptyView()
            }
            Button ("Open Detail View 2") {
                self.isActive = true
            }
        }
        .navigationBarTitle(Text("Detail View 1"), displayMode: .inline)
    }
}

struct DetailView2: View {
    var body: some View {
        Text("This is Detail View 2")
            .navigationBarTitle(Text("Detail View 2"), displayMode: .inline)
    }
}

我的第一个方法是在DetailView1中将 isActive 设置为true:

My first approach was to set isActive to true at its declaration in DetailView1:

@State private var isActive = true

如预期的那样,会触发NavigationLink,但是DetailView2出现后会立即弹出.

As expected, the NavigationLink is triggered, but DetailView2 is popped immediately after appearing.

我还(或者)尝试在 .onAppear

.navigationBarTitle(Text("Detail View 1"), displayMode: .inline)
.onAppear(){
    self.isActive = true
}

但是结果是相同的.

实际可行的方法是将 isActive 设置为true至少延迟0.75秒,我认为这不是可接受的解决方法.

What actually worked was delaying setting isActive to true by at least 0.75 seconds, which in my opinion is not an acceptable workaround.

.navigationBarTitle(Text("Detail View 1"), displayMode: .inline)
.onAppear(){
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) {
        self.isActive = true
    }
}

这是一个错误还是有实现预期效果的方法?

Is this a bug or is there a way to achieve the desired effect?

推荐答案

使用Xcode 11.4/iOS 13.4,可以使用 .toggle()正常工作,如下所示

With Xcode 11.4 / iOS 13.4 works properly using .toggle(), like below

.navigationBarTitle(Text("Detail View 1"), displayMode: .inline)
.onAppear {
    self.isActive.toggle()
}

这篇关于如何以编程方式触发NavigationLink出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-28 18:11