I have a UIButton
in my app that I call "buttonPlay". I am using AutoLayout but the button doesn't have any NSLayoutConstraints
attached to it.
I would like to code an animation to increase and the decrease the height and the width of the button. Here's how the animation code looks like:
// "Repeat" because the animation must repeat itself
UIView.animateWithDuration(1.0, delay: 0.6, options: UIViewAnimationOptions.Repeat, animations: {
// Animation code goes here
// nil: the animation is not supposed to end
}, completion: nil)
}
To get the original values of the x position, y position, width and height I am using the following code:
var frmPlay : CGRect = self.buttonPlay.frame
// get the current x and y positions
let originXbutton = frmPlay.origin.x
let originYbutton = frmPlay.origin.y
// get the current width and height of the button
let originWidthbutton = frmPlay.size.width
let originHeightbutton = frmPlay.size.height
// set the frame (frmPlay) to the button frame
self.buttonPlay.frame = frmPlay
Okay, it's now time to increase or decrease the width and the height of the animation. I'll put this code inside the animation
block:
self.buttonPlay.frame = CGRectMake(
originXbutton,
originYbutton,
originWidthbutton-100,
originHeightbutton)
self.buttonPlay.frame = CGRectMake(
originXbutton,
originYbutton,
originWidthbutton+100,
originHeightbutton)
The animation code will look something like this:
UIView.animateWithDuration(1.0, delay: 0.6, options: UIViewAnimationOptions.Repeat, animations: {
println("Animation function animateStuff() started!")
var frmPlay : CGRect = self.buttonPlay.frame
let originXbutton = frmPlay.origin.x
let originYbutton = frmPlay.origin.y
let originWidthbutton = frmPlay.size.width
let originHeightbutton = frmPlay.size.height
self.buttonPlay.frame = frmPlay
self.buttonPlay.frame = CGRectMake(
originXbutton,
originYbutton,
originWidthbutton-100,
originHeightbutton)
self.buttonPlay.frame = CGRectMake(
originXbutton,
originYbutton,
originWidthbutton+100,
originHeightbutton)
}, completion: nil)
Let's run the app. Uh oh! The button (also called buttonPlay) doesn't get bigger or smaller in any way. Though it moves from right to left. But hey! I haven't touched the x and the y positions code.
What causes it?
Put separate animations for increasing and decreasing button size .Try this code .
This will decrease the button size with animation .
This will increase the size again to original button .
use
UIViewAnimationOptions.Repeat
andUIViewAnimationOptions.Autoreverse
together to do that. You just have to set one frame change inside the animation block. You cannot have more than one state change to the same property inside an animation block.If you want to scale the button up and down,
My solution in
Swift 3
: