2

I try to add action when a tap gesture start and end but its not work !!! and bellow the example code.

@State private var opacity = 1.0

var body: some View {
Image(systemName: "plus.square.on.square")
            .opacity(opacity)
            .onTapGesture {
                opacity = 0.2
            }
            .gesture(
            TapGesture()
                .onEnded({ _ in
                    opacity = 1.0
                })
            )
}
Ammar Ahmad
  • 534
  • 5
  • 24
  • This doesn't *directly* answer your question, so I'm not going to leave it as an answer, but is it possible that you can achieve what you're looking for with `ButtonStyle`s? https://www.simpleswiftguide.com/advanced-swiftui-button-styling-and-animation/ – jnpdx Mar 03 '21 at 06:46
  • What are you looking for to change opacity to 0.2 on first tap, and then set back to 1.0 on second tap? With tap gesture that makes more sense to me in your question. – Tushar Sharma Mar 03 '21 at 07:08
  • No, I'm try to set the opacity to 0.2 when tap begin and set it back to 1.0 when tap end, that what I trying to do. – Ammar Ahmad Mar 03 '21 at 07:13
  • Why not use longPressGesture then? Use longPressGesture with minimumDuration how long you want to press, and then reset when you end. – Tushar Sharma Mar 03 '21 at 07:14
  • If I use button the "ButtonStyle" will work, but I use an image and I need it to be an image, so I can't use any kind of "Style" – Ammar Ahmad Mar 03 '21 at 07:19
  • @TusharSharma can you show some example code for using " LongPressGesture" ? – Ammar Ahmad Mar 03 '21 at 07:27
  • I can’t post an answer, until that’s your requirement. You can google the same, there are multiple answers on that. Use something like--> `.onLongPressGesture(minimumDuration: 7, pressing: { inProgress in opacity = 0.2 }) { opacity = 1.0 }`. Replace your gesture code with this. – Tushar Sharma Mar 03 '21 at 07:33

1 Answers1

0

@TusharSharma is very close except for when using onLongPressGesture for detecting precisely the start and end of the gesture, only the onPressingChanged block matters.

This is a working example based on the code in question:

var body: some View {
  Image(systemName: "plus.square.on.square")
    .opacity(opacity)
    .onLongPressGesture(minimumDuration: .infinity) {
      // Do nothing as an action, only the state change matters.
    } onPressingChanged: { starting in
      withAnimation { opacity = starting ? 0.2 : 1.0 }
    }
}
@State 
private var opacity = 1.0

(The withAnimation part is optional, but I thought you'd want it for your example.)

minimumDuration: .infinity "holds" opacity on 0.2 for the entire duration of time while the user holds the press.

lazarevzubov
  • 1,767
  • 2
  • 14
  • 24