How to make animations and gesture recognisers work together? (Swift)

后端 未结 1 1514
轮回少年
轮回少年 2021-01-24 19:48

I made a simple project, with swipe gesture recogniser and animation. I made my label to move and every 3 second increase number. With every swipe I need to decrease the number

1条回答
  •  情话喂你
    2021-01-24 20:26

    By default view objects block user interaction while an animation is "in flight". You need to use one of the "long form" animation methods, and pass in the option .allowUserInteraction. Something like this:

    UIView.animate(duration: 0.5,
      delay: 0.0,
      options: .allowUserInteraction,
      animations: {
        myView.alpha = 0.5
      })
    

    Note, however, that if what you're animating is a view's position, the user won't be able to tap on the view object as it moves. That's because a position animation does not really animate the object from one place to another over time. It just creates that appearance. Behind the scenes, the object actually jumps to it's final position the moment the animation begins.

    If you need to be able to tap/drag/swipe on objects while they're moving you will have to do that yourself. What you do is put a gesture recognizer on the parent view that encloses the entire range of motion (possibly the whole screen.) Then you need to use the presentation layer of your animating view's layer, translate the coordinates of the point from the gesture recognizer's coordinate space to the layer's coordinate space, and use the layer's hitTest method to figure out if the point is on the layer or not.

    I have a project on Github called iOS-CAAnimation-group-demo that does something like that (It animates an image view along a complex path and you can tap on the image view to pause the animation while it's "in flight".

    It's from several years ago, so it's written in Objective-C, but it should help to at least illustrate the technique.

    0 讨论(0)
提交回复
热议问题