Oddity with UIView Animations

Andy Bennett
2 min readApr 3, 2018

--

Photo by Rob Potter on Unsplash

I was playing with animations the other day and I came across an oddity …

I set up 3 views; the main one and 2 sub views, so far so good:

let view = UIView()
view.backgroundColor = .white
let viewOne = UIView()
viewOne.frame = CGRect(x: 30, y: 30, width: 30, height: 30)
viewOne.backgroundColor = .black
viewOne.alpha = 0.1
let viewTwo = UIView()
viewTwo.frame = CGRect(x: 120, y: 30, width: 30, height: 30)
viewTwo.backgroundColor = .black
viewTwo.alpha = 0.1
view.addSubview(viewOne)
view.addSubview(viewTwo)

Then I animate them:

UIView.animate(withDuration: 2.0, animations: {
viewOne.alpha = 1
viewOne.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)
viewTwo.alpha = 1
viewTwo.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)
})

Only the second (viewTwo) of the views animates — both alpha and transform properties animate; but neither of them animate on viewOne.

It makes no difference if I do one animate block or two:

UIView.animate(withDuration: 2.0, animations: {
viewOne.alpha = 1
viewOne.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)
})
UIView.animate(withDuration: 2.0, animations: {
viewTwo.alpha = 1
viewTwo.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)
})

In each case, the first view instantly jumps to the final state and the second animates.

According to the Apple documentation … “Animate changes to one or more views using the specified duration.” … so what gives?

I’d love to know what’s actually going on here, but for now, here’s a workaround — use the newer UIViewPropertyAnimator (iOS 10.0+):

UIViewPropertyAnimator
.runningPropertyAnimator(withDuration: 2.0, delay: 0, options: [],
animations:
{
viewOne.alpha = 1
viewOne.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)
viewTwo.alpha = 1
viewTwo.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)
})

Nothing else has changed, but now both views animate simultaneously.

--

--