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

时间:2020-07-12 12:17:37

标签: navigation swiftui

对于以下CardView(),我希望用户点击它以导航到WebView(),其中链接字符串在post.article_url中。

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
            }
        )}}

我尝试用CardView()包装NavigationLink()。导航成功,但是将CardView()上的图像和文本变成了完整的蓝色。也许可以通过其他方法(例如使用.onTapGuesture{}中的某些代码)解决此问题?

此外,因为这是应该刷卡的纸叠。 NavigationLink()还会阻止这些卡上的拖动手势。

谢谢!

1 个答案:

答案 0 :(得分:1)

引入一个变量(布尔),使用一个空的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() }