SwiftUI How to enable buttons on the views which have gesture

Viewed 132

I want to put buttons on the view which has DragGesture by ZStack. But when I put buttons on the view, it doesn't work.


    struct TmpView5: View {

    @State var position: CGSize = CGSize(width: 200, height: 250)

    
    var drag: some Gesture {
        DragGesture()
        .onChanged{ value in
            self.position = CGSize(
                width: value.startLocation.x
                    + value.translation.width,
                height: value.startLocation.y
                    + value.translation.height
            )
        }
        .onEnded{ value in
            self.position = CGSize(
                width: value.startLocation.x
                    + value.translation.width,
                height: value.startLocation.y
                    + value.translation.height
            )
        }
        
    }
    
    var body: some View {
    
        ZStack {
            
                Rectangle()
                    .fill(Color.black)
                    .position(x: position.width, y: position.height)
                    .gesture(drag)
                
                HStack {
                    Button(action: {
                        print("taped!!!")
                    }){
                        Image(systemName:"photo.on.rectangle")
                    }.padding(.trailing)
                    
                    
                    Button(action: {
                        print("taped!!!")
                    }){
                        Image(systemName:"a")
                            .padding(.trailing)
                    }
                    
                }
        }
    }
}

If I remove gesture(drag), I can tap buttons. Is it possible to add gesture on the Rectangle and enable buttons ?

1 Answers

Works fine, just buttons too close to each other and have too small internal area, so add more internal padding for each as shown below (tested with Xcode 12.1 / iOS 14.1)

HStack {
    Button(action: {
        print("taped!!!")
    }){
        Image(systemName:"photo.on.rectangle").padding()    // << here !!
    }
    
    Button(action: {
        print("taped!!!")
    }){
        Image(systemName:"a").padding()     // << here !!
    }
}
Related