Arinjay
Arinjay

Reputation: 69

add animation to UIview created programmatically

I am trying to build a UILabel.

But I want to animate when this label popups up

where should I animate the label ??

Here is my code

static func setupView(view: UIView){
       let networkStatusView = UILabel(frame: CGRect(x: 0, y: 40, width: view.bounds.width, height:50))
        networkStatusView.tag = 20
        networkStatusView.text = "offline"
        networkStatusView.font = UIFont.boldSystemFont(ofSize: 18)
        networkStatusView.translatesAutoresizingMaskIntoConstraints = false
        networkStatusView.textAlignment = .center
        networkStatusView.backgroundColor=UIColor.green
        networkStatusView.layer.borderColor = UIColor.white.cgColor

        UIView.animate(withDuration: 0.5) {
        view.addSubview(networkStatusView)
        }
        view.layoutIfNeeded()    
    }

Upvotes: 1

Views: 1375

Answers (3)

Varun Goyal
Varun Goyal

Reputation: 732

To help visualize how UIView.animate works;

Think of the state your UILabel is in before calling UIView.animate method. For example based on qtngo's answer the networkStatusView will be a sub-view for the current ViewController's view and will not be visible since the alpha is set to 0.

Now with-in the animate block:

UIView.animate(withDuration: 0.5) { networkStatusView.alpha = 1.0 view.layoutIfNeeded() }

The developer is telling the system to animate the networkStatusView for the next 0.5 seconds and change the view's alpha from 0 to 1.0 hence making it visible.

Hope this helps.

Upvotes: 1

Jaspreet Singh
Jaspreet Singh

Reputation: 51

Just to make it like dropping down from Top

Give initial height to View to be : 0

and animate it like :

view.addSubview(networkStatusView)
    UIView.animate(withDuration: 0.5) {
         networkStatusView.frame.size.height = 50
        view.layoutIfNeeded()
    }

Upvotes: 1

qtngo
qtngo

Reputation: 1679

The addSubview function is not animatable. Assuming you want a fade-in effect, you should change your last 4 lines with:

view.addSubview(networkStatusView)
networkStatusView.alpha = 0.0
UIView.animate(withDuration: 0.5) {
    networkStatusView.alpha = 1.0
    view.layoutIfNeeded()
}

Hope this helps

Upvotes: 5

Related Questions