如何在容器视图中为父视图控制器中的约束更改设置动画? (斯威夫特4)

时间:2017-07-11 03:32:32

标签: swift animation

我在视图控制器中有一个容器视图,其中包含一个按钮,每次按下该按钮都会在父视图控制器中向下移动标签。我通过准备segue将标签的约束传递给容器。从那里我可以修改约束,但它不会动画。

我该怎么做?

visual example

class ViewController: UIViewController {

    @IBOutlet weak var LabelTopConstraint: NSLayoutConstraint!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "containerSegue" {
            let container = segue.destination as? Container
            container?.LabelTopConstraint = LabelTopConstraint
        }
    }
}

class Container: UIViewController {

    weak var LabelTopConstraint: NSLayoutConstraint!

    @IBAction func MoveLabelButtonPressed(_ sender: Any) {
        LabelTopConstraint.constant += 30
        UIView.animate(withDuration: 0.35, animations: {
            self.view.layoutIfNeeded()
        })
    }
}

1 个答案:

答案 0 :(得分:1)

100%工作回答您需要更新父视图的布局,如..

@IBAction func MoveLabelButtonPressed(_ sender: Any) {


    self.LabelTopConstraint.constant += 30 // Your constraint constant change


    UIView.animate(withDuration: 3.0) {
        self.parent?.view.layoutIfNeeded() // Force lays of all subviews on parent view .
    }

}

<强>输出:

enter image description here