Search code examples
iosswiftanimationtouch

Animation not running after addsubview command in swift


My app includes a button that animates a "spring in" collection view and hides the view when you touch outside of it. The animation works great, until the touchesbegan function is called, then it only fades in.

My touches began function includes the addsubview command and that somehow seems to be causing the issue.
Why is my "spring in" animation not working after the addsubview command is read? Is this an issue with my constraints resetting? My animation block is called every time.

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    let bgImage = UIImageView(image: processedImage)
    self.viewArray.append(bgImage)
}

func showFilter(){
    view.bringSubviewToFront(collectionView)
    var collectionViewPos = collectionView.center.x
    self.collectionView.center.x = view.frame.width + 300
    UIView.animateWithDuration(0.0, delay: 0.0, options: [], animations: { () -> Void in
        self.collectionView.alpha = 1
        }, completion: { (complete: Bool) in

            UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 10, options: [], animations: { () -> Void in
                self.collectionView.center.x = collectionViewPos
                self.view.layoutIfNeeded()
                }, completion: nil)
            return
    })
}

Solution

  • My issue was related to the constraints. I used the answer from this question How do I animate a NSLayoutConstraint in Swift? to animate the constraint change rather than a movement. It works flawlessly now.

    self.view.bringSubviewToFront(self.collectionView)
    constraint.constant =  constraint.constant + 300
    UIView.animate(withDuration: 1.0, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 10, options: [], animations: { () -> Void in
        self.view.layoutIfNeeded()
    }, completion: nil)