ZStack中带有按钮的可替换图像

时间:2020-10-29 21:14:29

标签: button swiftui 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完好无损,并同时可以点击图像和关闭按钮?enter image description here

1 个答案:

答案 0 :(得分:0)

尝试向NetworkImage(代码beloew中的矩形)添加一个onTapGesture修饰符-似乎按预期工作。我将NetworkImage简化为使用标准Rectangle,但是点击结果应该相同。在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])
        }
    }