UIView.animateWithDuration Not Animating Swift (again)
If you infoDetailView is under auto layout constraints you need to call layoutIfNeeded on the parent view inside animateWithDuration:
func showInfoView() { self.view.layoutIfNeeded() // call it also here to finish pending layout operations UIView.animate(withDuration: 2.0, animations: { self.infoDetailView.alpha = 0.75 self.view.layoutIfNeeded() })}
Theoretically this should not be needed if you just change the .alpha value, but maybe this could be the problem in this case.
There are several strange things I can see,
first, remove:
infoDetailView.layoutIfNeeded()infoDetailView.setNeedsDisplay()
Usually you don't need to call those methods manually unless you know exactly what you are doing.
Also, when you are changing the size:
infoDetailView.frame = viewRectinfoDetailView.bounds = viewRect
You never need to set both bounds
and frame
. Just set frame
.
Also, you should probably make sure that the view actually doesn't ignore the frame by setting:
infoDetailView.translatesAutoresizingMaskIntoConstraints = true
Instead of resetting the frame, just set autoresize mask:
infoDetailView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
Resulting in:
override func viewDidLoad() { super.viewDidLoad() // Cut other vDL code that isn't relevant setupInfoView()}func setupInfoView() { infoDetailView.alpha = 0.0 infoDetailView.translatesAutoresizingMaskIntoConstraints = true infoDetailView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] infoDetailView.frame = view.bounds view.addSubview(infoDetailView)}func hideInfoView() { ...}
I think this should actually help because immediate animations are often connected to size problems.
If the problem persists, you should check whether the infoDetailView
in your animation is the same object as the infoDetailView
you are adding to the controller.
For others looking to start an animation immediately when a view loads...
The animation won't work if you call UIView.animate(...)
inside viewDidLoad
. Instead it must be called from the viewDidAppear
function.
override func viewDidAppear(_ animated: Bool) { UIView.animate(withDuration: 3) { self.otherView.frame.origin.x += 500 }}