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

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

介绍

这一节中,咱们将利用本节所学的内容,建立一个新的View,添加约束并显示出来
showItem(_:)函数将在咱们点击TableViewRow的时候显示出来一个新的View,实现以下效果:
图片描述
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轴方向的位置spa

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()code

移除视图

咱们能够在动画的完成闭包里延迟1s并移除imageViewblog

//尾挂闭包
    { (_) -> 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)
                }
        }

最终效果
图片描述图片

相关文章
相关标签/搜索