Caleb Rudnicki
Caleb Rudnicki

Reputation: 385

Tappable Image in a ZStack with a Button

I have a ZStack with an image and a close button overlaying it. I cannot make the image tappable with the button overlaying it.

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

I have tried to add a tap gesture to the Image itself but that disables the tapability on the close button. How can I keep the ZStack in tact and have both the image and close button tappable?enter image description here

Upvotes: 0

Views: 1557

Answers (1)

rohanphadte
rohanphadte

Reputation: 1018

Try adding an onTapGesture modifier to the NetworkImage (Rectangle in the code beloew) - it seems to work as expected then. I simplified the NetworkImage to use a standard Rectangle, but the tap results should be the same. Tested on 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])
        }
    }

Upvotes: 1

Related Questions