【问题标题】:How to call SwiftUI NavigationLink conditionally?如何有条件地调用 SwiftUI NavigationLink?
【发布时间】:2020-10-27 16:30:47
【问题描述】:

我正在考虑当用户点击它时如何有条件地允许启动NavigationLink。在UIKit 中,这很明显,但在SwiftUI 中,这在我看来是个大问题。我知道我可以在我认为的某处声明NavigationLink,即

@State private var isFired = false

/* (...) */

NavigationLink(destination: AnotherView(), isActive: $isFired) { EmptyView() }

然后这样称呼它

Button(action: {
    if /* check condition */ {
        self.isFired = true
    } else {
        print("condition is not fulfilled")
    }
}) {
    Image("my-image")
}

但是...问题是:我的导航链接是在循环中动态创建的,并且将图像包装在ScrollView 中,即

ScrollView(.vertical) {
    ForEach(photos, id: \.self) { element in
        NavigationLink(destination: ImagePreviewView(photo: element)) {
            Image(uiImage: element.image)
        }
    }
}

如何有条件地允许在上面的代码中启动导航链接?例如:用户点击图像 -> 显示密码请求 -> 如果密码正确,则导航链接触发,否则应用程序执行其他操作(显示警报等无关紧要)

【问题讨论】:

    标签: swift swiftui swiftui-navigationlink


    【解决方案1】:

    无论如何它应该是一个按钮......类似

    ScrollView(.vertical) {
        ForEach(photos, id: \.self) { element in
            Button(action: {
               // here call a function with callback provided if password
               // verification passed
               self.checkPassword { verified in
                 if verified {
                    self.photo = element  // store tapped element
                    self.isFired = true   // << this might be called async
                 }
               }
            }) {
                Image(uiImage: element.image)
            }
        }
    }
    .background(
       // activate link for tapped photo
       NavigationLink(destination: ImagePreviewView(photo: self.photo), 
          isActive: $isFired) { EmptyView() }
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多