简体   繁体   English

将动画添加到以编程方式创建的UIview

[英]add animation to UIview created programmatically

I am trying to build a UILabel. 我试图建立一个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()    
    }

The addSubview function is not animatable. addSubview函数不可设置动画。 Assuming you want a fade-in effect, you should change your last 4 lines with: 假设您想要淡入效果,则应使用以下命令更改最后4行:

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

Hope this helps 希望这可以帮助

Just to make it like dropping down from Top 只是让它像从顶部掉下来一样

Give initial height to View to be : 0 将View的初始高度设为:0

and animate it like : 并对其进行动画处理:

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

To help visualize how UIView.animate works; 有助于可视化UIView.animate的工作方式;

Think of the state your UILabel is in before calling UIView.animate method. 在调用UIView.animate方法之前,请先考虑一下UILabel所处的状态。 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. 例如,基于qtngo的答案networkStatusView将是当前ViewController视图的子视图,并且由于alpha设置为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. 开发人员告诉系统在接下来的0.5秒内为networkStatusView设置动画, networkStatusView视图的Alpha从0更改为1.0,从而使其可见。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM