Adding button to a moving image SwiftUI

Viewed 36

I have successfully added a button to an image however when I click the button and the image moves via CGAffineTransform, the image moves but the button stays in the same place. When I click the space where the image used to be before the transform, the state toggle reacts. How do I get the button to move along with the image?

enter image description here

struct SliderView: View {


@State var partyType: Bool = false

var body: some View {

    ZStack{
        
            GeometryReader{ geo in
                
                VStack(alignment: .leading){
                
                Button(action: {

                    withAnimation (){

                        
                        self.partyType.toggle();

                        
                    }
                }) {

                Image("chevronPointer")
                    
                    .clipped()
                    .modifier(SlideEffect(offset: CGSize(width: partyType ? geo.size.width - 70 : 0, height: 0.0)))
                    .animation(.smooth())
                    .padding(.horizontal)
                   
                    
                }
                
                Image("sliderLine")
                    .resizable()
                    .scaledToFit()
                    .frame(width: geo.size.width, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
            }
            
            
        }
            .frame(height: 40)
        
    }
    
}

}

struct SlideEffect: GeometryEffect {
var offset: CGSize

var animatableData: CGSize.AnimatableData {
    get { CGSize.AnimatableData(offset.width, offset.height) }
    set { offset = CGSize(width: newValue.first, height: newValue.second) }
}
public func effectValue(size: CGSize) -> ProjectionTransform {
    return ProjectionTransform(CGAffineTransform(translationX: offset.width, y: offset.height))
}
}

struct SliderView_Previews: PreviewProvider {
static var previews: some View {
    SliderView()
}
}
1 Answers

Just move the modifier outside the button.

Button(action: {
    withAnimation(){
        
        self.partyType.toggle()
    }
}) {
    Image(systemName: "chevron.up")
        .clipped()
        .animation(.default)
        .padding(.horizontal)
}
.modifier(SlideEffect(offset: CGSize(width: partyType ? geo.size.width - 70 : 0, height: 0.0))) /// here!
Related