SwiftUI:使用 .onTapGesture{} 导航到另一个视图

SwiftUI: navigate to another view with .onTapGuesture{}

对于以下 CardView(),我希望用户点击它以导航到 post.article_url 中具有 link 字符串的 WebView()

ForEach(self.posts.reversed(), id: \.id) {post in
    GeometryReader{geo -> AnyView in
        return AnyView(
            CardView (index: self.getPostIndex(post: post),
                      title: post.title,
                      image: post.cover_image,
                      author: post.author, 
                      source: post.source, description: post.description,
                      imageWidth: self.cardWidth, 
                      imageHeight: self.imageHeight(index: self.getPostIndex(post: post))
            )
            .animation(.spring())
            .frame(width: self.widthAmount(index: self.getPostIndex(post: post)), 
                   height: self.heightAmount(index: self.getPostIndex(post: post)))
            .offset(x: self.CardOffsetAmountHorizontal(index: self.getPostIndex(post: post)),
                    y: self.CardOffsetAmountVertical(index: self.getPostIndex(post: post)))
            .onTapGesture{
                // navigate to a webview with url: post.article_url
            }
        )}}

我试图用 NavigationLink() 包裹 CardView()。导航成功,但是把CardView()上的图片和文字变成了全蓝。也许这可以通过其他方式解决(例如 .onTapGuesture{} 中的一些代码)?

此外,因为这是一个应该被刷卡的卡片堆。 NavigationLink() 还阻止了这些卡片上的拖动手势。

提前致谢!

引入一个变量 (Bool),您使用空的 NavigationLink 对其进行监视。捕获选项卡时切换此变量,然后激活重定向

// This variable 
@State private var goToNewView: Bool = false

ForEach(self.posts.reversed(), id: \.id) {post in
    GeometryReader{geo -> AnyView in
        return AnyView(
            CardView (index: self.getPostIndex(post: post),
                      title: post.title,
                      image: post.cover_image,
                      author: post.author, 
                      source: post.source, description: post.description,
                      imageWidth: self.cardWidth, 
                      imageHeight: self.imageHeight(index: self.getPostIndex(post: post))
            )
            .animation(.spring())
            .frame(width: self.widthAmount(index: self.getPostIndex(post: post)), 
                   height: self.heightAmount(index: self.getPostIndex(post: post)))
            .offset(x: self.CardOffsetAmountHorizontal(index: self.getPostIndex(post: post)),
                    y: self.CardOffsetAmountVertical(index: self.getPostIndex(post: post)))
            .onTapGesture{
                // navigate to a webview with url: post.article_url

                // Toggle the variable here
                self.goToNewView.toggle()
            }
        )}}


// Put this in your view. It will not be visible
NavigationLink(destination: MyOtherView(), isActive: self.$goToNewView) { EmptyView() }