iosswiftanimationuiviewanimatewithduration

Smooth expanding UIView animation in Swift


Aim:

How can I animate a UIView that I want to expand to fill the whole screen. The UIView needs to expand in smooth, even and balance way while it animates.

I have one red square positioned on screen, starts small then expands to fit the screen. (Image 1.)

let subview = UIView()
subview.backgroundColor = .red
subview.frame = CGRect(x: 60, y: 200, width: 50, height: 50)
self.view.addSubview(subview)

Question:

In Swift 2 and Swift 3, using an animateWithDuration, how do I animate the the red square UIView expanding in a balanced and even manner in all directions to fill the whole screen?

UIView.animateWithDuration(1.0, delay: 0, options: nil, animations: {

    ?????

}, completion: nil)

Image 1:

enter image description here


Solution

  • You can try this, I set the duration to 5 seconds but you got the idea.

    let viewWidth = view.frame.width
    let viewHeight = view.frame.height
    UIView.animate(withDuration: 5) { 
        subview.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)
    }