I am seeing an unexpected initial condition when I set layer opacity multiple times within a UIView.animate block:
movingView.frame = CGRect(x: 120, y: 120, width: 100, height: 100)
movingView.backgroundColor = UIColor.blue
opacityView.backgroundColor = UIColor.red
opacityView.layer.opacity = 0.5
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
UIView.animate(withDuration: 3.0) {
opacityView.layer.opacity = 0
opacityView.layer.opacity = 1
movingView.frame = CGRect(x: 10, y: 120, width: 100, height: 100)
movingView.frame = CGRect(x: 190, y: 120, width: 100, height: 100)
}
}
When this code is run in the playground, the blue (bottom) square animates from the middle of the view to the right edge, as expected, even though the frame is initially set to the left hand position, only the last value is used in the animation.
The red square however, does not animate from 0.5 opacity directly to 1.0. It first jumps to 0.0 opacity with no animation before then animating to 1.0 opacity.
Obviously this is a contrived case, but I ran into this when animating only one of a group of elements, I set all elements to opacity 0, then set the one I wished to be visible to animate to opacity 1. But this did not give the expected animations. I was able to work around this by removing the one I wished to be visible from list of all items.
But I am curious and would like to understand what is occurring here, and why the opacity behaviour differs from animating frame values, and if there is another cleaner way to work around this.
============================================
For clarity, I understand what will make this work, but this is a contrived example, in order to make it work in the real world, my code becomes unnecessarily more complex. I want to know why it is exhibiting this behaviour, and why it is different from animating the frame.