首页 > 解决方案 > 带有按钮的 ZStack 中的可点击图像

问题描述

我有ZStack一个图像和一个覆盖它的关闭按钮。我无法使用覆盖它的按钮使图像可点击。

          ZStack(alignment: .topTrailing) {
                NetworkImage(url: article.imageURL)
                    .aspectRatio(contentMode: .fill)
                    .frame(width: UIScreen.main.bounds.width,
                           height: UIScreen.main.bounds.height * 0.5)
                    .scaleEffect(scrollViewContentOffset < 0 ?
                                    1 + (-scrollViewContentOffset * 0.005)
                                    : 1,
                                 anchor: .bottom)
                
                Button(action: {
                    self.presentationMode.wrappedValue.dismiss()
                }){
                    Image(systemName: "xmark.circle.fill")
                        .foregroundColor(.init(white: 0.9)).padding([.top, .trailing])
                        .font(.system(size: topCloseButtonSize))
                        .offset(y: scrollViewContentOffset < 0 ?
                                    .extraLarge + scrollViewContentOffset :
                                    .extraLarge)
                }
            }

我试图向图像本身添加一个点击手势,但这会禁用关闭按钮上的可点击性。如何保持 ZStack 完好无损,并让图像和关闭按钮都可以点击?在此处输入图像描述

标签: buttonswiftuizstack

解决方案


尝试向onTapGestureNetworkImage 添加一个修饰符(下面代码中的矩形) - 它似乎按预期工作。我简化了 NetworkImage 以使用标准矩形,但点击结果应该是相同的。在 Xcode 12.1 上测试。

    ZStack(alignment: .topTrailing) {
        Rectangle()  // Use NetworkImage here - simplified to Rectangle for testing
            .aspectRatio(contentMode: .fill)
            .frame(width: UIScreen.main.bounds.width,
                   height: UIScreen.main.bounds.height * 0.5)
            .onTapGesture(count: 1, perform: {
                print("RECTANGLE TAPPED!")
            })
        Button(action: {
            print("CLOSE TAPPED")
        }){
            Image(systemName: "xmark.circle.fill")
                .foregroundColor(.init(white: 0.9)).padding([.top, .trailing])
        }
    }

推荐阅读