22

I'm struggling to figure out how to allow user interaction with a view as it's being animated.

Here's the situation: I have a UIView cardView which holds card subviews. The cards are draggable tiles, similar to how the cards in Tinder are draggable/swipeable.

I am trying to fade out the card using animateWithDuration by animating to cardView.alpha = 0. Logically, this will also fade out all of the subviews (card objects). In this specific case, I am only targeting one card subview. However, during the animation, I am unable to drag/interact with the card.

Here is the code I'm using:

UIView.animateWithDuration(
        duration,
        delay: 0,
        options: UIViewAnimationOptions.AllowUserInteraction,
        animations: {self.cardView.alpha = 0}
    ) {
        _ in
        println("Card faded out")
        card.removeFromSuperview()
    }

Why doesn't this work? Any help will be appreciated. Thank you!!

vimfluencer
  • 3,106
  • 3
  • 17
  • 25
  • This code is part of a function in my view controller - `duration` is parameterized. Also, I'm using a trailing closure instead of directly supplying a `completion` command. Sorry if either of these things caused confusion. – vimfluencer Aug 24 '14 at 23:46

4 Answers4

24

I think you can find the answer in this previous post.

The interesting bit of the post is:

UIView's block animation by default blocks user interaction, and to get around it you need to pass UIViewAnimationOptionAllowUserInteraction as one of the options.

Community
  • 1
  • 1
gabriel_101
  • 773
  • 3
  • 19
12

I fixed this problem by setting alpha to 0.1 instead of 0.0. I'm not sure if that will work in your case, but it shows that the event handling code thought that the view was not visible and disabled interaction even with the UIViewAnimationOptionAllowUserInteraction flag set. Oddly, setting the alpha to 0.01 did not work, so there is a threshold of visibility you have to stay above.

EricS
  • 9,650
  • 2
  • 38
  • 34
6

Swift 5

UIView.animateKeyframes(withDuration: 0.5, delay: 0, options: [.repeat, .autoreverse, .allowUserInteraction], animations: {
        self.customButton.backgroundColor = .none
    }, completion: nil)
Elshad Karimov
  • 322
  • 2
  • 10
3

The issue is with the Alpha value of 0. Alpha values of a certain proximity to Zero will remove the view from the view responder hierarchy. The fix here is to make the alpha setting to this:

self.cardView.alpha = 0.011

The view will still be invisible but not removed from the responder chain. From my testing the minimum amount is the following:

extension CGFloat {

    static let minAlphaForTouchInput: CGFloat = 0.010000001
}
rismay
  • 271
  • 2
  • 8