如何使用Swift中的约束来动画UIView? [英] How to animate a UIView with constraints in Swift?

查看:553
本文介绍了如何使用Swift中的约束来动画UIView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的设计示例中,我有以下单一视图:





如您所见,它包含一些简单的约束:


  1. 对齐水平和垂直中心,

  2. 高度(设置为常量)

  3. 前导和尾随空格(设置为常数)

我想要达到的目的是让这个红色/粉红色的视图从顶部进入。传统上,在一个无约束的世界中,我只是修改 UIView.animateWithDuration 中的框架,但是我不确定我是如何在约束世界中做类似的。



重申一下我的问题,如何让我的视图从场景开始,并从顶部开始播放视图?



我考虑过设置垂直中心约束(随后调用 layoutIfNeeded ),但它没有达到预期的效果。 / p>

感谢您的帮助。

解决方案

您可以做的是在 viewDidAppear 方法中添加以下代码。您首先在视图的中心Y约束中创建 IBOutlet 属性,然后更改其常量值。

  self.centerYConstraint.constant = 500.0 
self.view.layoutIfNeeded()

UIView.animateWithDuration(Double(0.5),animations:{
self .centerYConstraint.constant = 0
self.view.layoutIfNeeded()
})


In my contrived example, I have the following single view:

As you can see, it consists of a few simple constraints:

  1. Align horizontal and vertical centers,
  2. Height (set to a constant)
  3. Leading and trailing spaces (set to constant)

What I'm seeking to achieve is to have this redish/pinkish view "come in" from the top. Traditionally, in a constraint-less world, I would simply modify the frame inside of UIView.animateWithDuration, however I'm not sure how I do the similar in a constraint world.

To reiterate my question, how can I make my view start out of scene and animate the view flying in from the top?

I've considered animating the vertical centers constraint (and subsequently calling layoutIfNeeded), but it's not achieving the desired effect.

Thanks for your help.

解决方案

What you can do is to add the following code in your viewDidAppear method. You firstly make a IBOutlet property of your view's center Y constraint, and then change its constant value.

self.centerYConstraint.constant = 500.0
self.view.layoutIfNeeded()

UIView.animateWithDuration(Double(0.5), animations: {
        self.centerYConstraint.constant = 0
        self.view.layoutIfNeeded()
    })

这篇关于如何使用Swift中的约束来动画UIView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆