动画约束导致不同的初始位置

时间:2017-06-23 11:45:40

标签: ios autolayout uikit

我有一个绿色视图,它固定在顶视图的边缘。顶部是蓝色视图,它也是顶视图的子视图,使用以下代码对齐...

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var blueView: UIView!
    @IBOutlet weak var greenView: UIView!

    override func viewDidLoad() {

        super.viewDidLoad()

        blueView.translatesAutoresizingMaskIntoConstraints = false

        blueView.widthAnchor.constraint(equalTo: greenView.widthAnchor).isActive = true
        blueView.leftAnchor.constraint(equalTo: greenView.leftAnchor).isActive = true

        blueView.heightAnchor.constraint(equalTo: greenView.heightAnchor).isActive = true

        let top = blueView.topAnchor.constraint(equalTo: greenView.topAnchor)
        top.priority = 800
        top.isActive = true

        view.layoutIfNeeded()

        UIView.animate(withDuration: 5) {

            let bottom = self.blueView.topAnchor.constraint(equalTo: self.greenView.bottomAnchor)
            bottom.priority = 1000
            bottom.isActive = true

            self.view.layoutIfNeeded()
        }
    }
}

如果我注释掉动画代码,这就是它的外观......

enter image description here

使用动画块,蓝色视图在正确的位置结束,但它从屏幕顶部开始,而不是与绿色视图的顶部对齐。

enter image description here

为什么动画阻止导致蓝色视图在屏幕上进一步启动?

1 个答案:

答案 0 :(得分:1)

确定 - 蓝色视图不是从绿色视图的顶部开始,因为您在初始布局完成之前开始动画

您可以将动画块移动到延迟后触发的功能,或移动到viewDidAppear

import UIKit

class AnimViewController: UIViewController {

    @IBOutlet weak var blueView: UIView!
    @IBOutlet weak var greenView: UIView!

    override func viewDidLoad() {

        super.viewDidLoad()

        blueView.translatesAutoresizingMaskIntoConstraints = false

        blueView.widthAnchor.constraint(equalTo: greenView.widthAnchor).isActive = true
        blueView.leftAnchor.constraint(equalTo: greenView.leftAnchor).isActive = true

        blueView.heightAnchor.constraint(equalTo: greenView.heightAnchor).isActive = true

        let top = blueView.topAnchor.constraint(equalTo: greenView.topAnchor)
        top.priority = 800
        top.isActive = true

    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        UIView.animate(withDuration: 5) {

            let bottom = self.blueView.topAnchor.constraint(equalTo: self.greenView.bottomAnchor)
            bottom.priority = 1000
            bottom.isActive = true

            self.view.layoutIfNeeded()
        }
    }
}