I want to change the opacity of my button to half when pressed, and animate that change. So I was searching for how to do that and found this piece of code:
@IBAction func keyPressed(_ sender: UIButton) {
UIView.animate(withDuration: 0.3)
{
sender.alpha = 0.5
}
I got curious as to why we called the animate
function on a UIView
not on a UIButton
, as what we want to animate is, specifically, a UIButton
. So I tried UIButton.animate()
and to my eyes it gives the same result with the animation.
So what's the difference? Is there a reason the person posting this code preferred using UIView.animate()
over UIButton.animate()
?
CodePudding user response:
The animate
function is a class level function of UIView
so it is common to use it as UIView.animate...
.
Since UIButton
ultimately extends UIView
, using UIButton.animate...
also works. You could even use UIScrollView.animate...
, for example, in your UIButton
code. Obviously that would be confusing but it would work.
In any code within a UIView
subclass, using Self.animate...
also works.
But the basic answer to your question is that people use UIView.animate...
because animate
is defined in the UIView
class.