2

I'm trying to use an animation transition for when a UIView appears on screen. The UIView appears correctly but the animation doesn't occur when it appears.

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let coreView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
    coreView.backgroundColor = UIColor.cyan
    coreView.layer.borderColor = UIColor.darkGray.cgColor
    coreView.layer.borderWidth = 8
    coreView.layer.cornerRadius = 15
    coreView.isHidden = true
    self.view.addSubview(coreView)

    //The transition occurs here
    UIView.transition(with: coreView, duration: 2, options: [.curveEaseInOut, .transitionCurlDown], animations: {

      coreView.isHidden = false
    }, completion: {_ in})

    }
SwiftyJD
  • 5,257
  • 7
  • 41
  • 92

4 Answers4

5

Instead of manipulating isHidden property of the coreView use the alpha property.

Try replacing coreView.isHidden = true with coreView.alpha = 0 and in the animation block replace coreView.isHidden = false with coreView.alpha = 1

That should be it I guess. It should animate. Thanks.

Asad Javed
  • 273
  • 4
  • 17
  • As a general rule, not all properties are *animatable*. When a property of UIView is animatable, it's always explicitly mentioned in the documentation. `isHidden` is not animatable. – deadbeef Jun 06 '17 at 19:41
  • It's a transition animation which works when adding or taking a view off a hierarchy. When the view is added in storyboard it works but since this view was created programmatically it doesn't work – SwiftyJD Jun 06 '17 at 19:51
1

This isn't working because coreView is not properly setup until after the viewWillAppear method completes so you can't use the transition animation (you can animate other properties like the alpha).

What you can do is this:

DispatchQueue.main.async {
    coreView.isHidden = false

     UIView.transition(with: coreView, duration: 2, options: [.curveEaseInOut, .transitionCurlDown], animations: {
    }, completion: {_ in})

}

This dispatches the transition back onto the main queue and it fires after the viewWillAppear method have completed and the coreView is properly setup.

By the way remember that viewWillAppear is called whenever the view controller is comes into view so if it hides and returns you will add another coreView.

Upholder Of Truth
  • 4,643
  • 2
  • 13
  • 23
1

Move your transition code to viewDidAppear

override func viewDidAppear(_ animated: Bool) {
//The transition occurs here
UIView.transition(with: coreView, duration: 2, options: [.curveEaseInOut, .transitionCurlDown], animations: {        
    coreView.isHidden = false
}, completion: {_ in})    
}
onlyphantom
  • 8,606
  • 4
  • 44
  • 58
0

Try adding self.view.layoutIfNeeded() after your coreView hiding code in the animation block.

badhanganesh
  • 3,427
  • 3
  • 18
  • 39