iOS动画编程-AutoLayout动画[ 5 ] Animating dynamically created views

前段时间考试,没有来得及写文,最近会抽时间把Animation部分写完

介绍

这一节中,我们将利用本节所学的内容,创建一个新的View,添加约束并显示出来
showItem(_:)函数将在我们点击TableViewRow的时候显示出来一个新的View,实现如下效果:
《iOS动画编程-AutoLayout动画[ 5 ] Animating dynamically created views》
Add the following code to showItem(_:) to create an image view out of the selected image:
在方法中加入如下代码来创建一个新的View


    let imageView = UIImageView(image:
    UIImage(named: "summericons_100px_0\(index).png"))
    imageView.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5)
    imageView.layer.cornerRadius = 5.0 
    imageView.layer.masksToBounds = true
    imageView.translatesAutoresizingMaskIntoConstraints = false 
    view.addSubview(imageView)

在上面的代码中,我们加载了一张图片,创建了一个新的ImageView,修改了圆角并设置了背景,注意,我们没有设置这个控件在父视图的位置。
接下来我们将通过代码对这个ImageView设置一个个约束:

let conX = imageView.centerXAnchor.constraintEqualToAnchor( view.centerXAnchor)

这里使用了NSLayoutAnchor这个类,这个类允许我们使用很简单的方法创建约束,这里我们创建了ImageView X中心与主View X中心位置之间的约束


    let conBottom = imageView.bottomAnchor.constraintEqualToAnchor( 
    view.bottomAnchor, constant: imageView.frame.height)
    let conWidth = imageView.widthAnchor.constraintEqualToAnchor( view.widthAnchor,
    multiplier: 0.33,
    constant: -50.0)
    let conHeight = imageView.heightAnchor.constraintEqualToAnchor( imageView.widthAnchor)
    //使约束生效
    NSLayoutConstraint.activateConstraints([conX, conBottom, conWidth, conHeight])

这步完成之后,我们的新视图就已经出现在屏幕下方了接下来我们用动画把它移到屏幕中央

Adding additional dynamic animations

接下来我们通过约束调整视图在Y轴方向的位置

    UIView.animateWithDuration(0.8, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: [], animations: {
    conBottom.constant = -imageView.frame.size.height/2 conWidth.constant = 0.0
    //使约束生效
    self.view.layoutIfNeeded()
    }, completion: nil)

运行一下,我们发现图片从屏幕的左上角飞到屏幕中央,这是为什么呢
思考一下: 你添加了一个新的View,设置了一些约束,然后使这些约束动态的设置来改变布局,然而这个View的默认位置在左上角(0,0)处 ,它没有机会去应用这些约束,直到你在动画必报中调用,为了解决这个问题,我们应该在动画前将设置初始位置的约束生效:
在动画闭包前先调用一次layoutIfNeeded()

移除视图

我们可以在动画的完成闭包里延迟1s并移除imageView

//尾挂闭包
    { (_) -> Void in
                UIView.animateWithDuration(0.8, delay: 1, options: [], animations: { () -> Void in
                    conBottom.constant += self.view.frame.size.height/2
                    self.view.layoutIfNeeded()
                    }){(_)-> Void in
                        self.view.willRemoveSubview(imageView)
                }
        }

最终效果
《iOS动画编程-AutoLayout动画[ 5 ] Animating dynamically created views》

    原文作者:Hydrogen
    原文地址: https://segmentfault.com/a/1190000004029885
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞