How to animate a UIView with constraints in Swift?

前端 未结 5 787
悲哀的现实
悲哀的现实 2020-12-08 06:20

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

\"enter

As you can

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 07:18

    Try this:

    class ViewController: UIViewController {
    
        // red view
        @IBOutlet weak var myView: UIView!
        //  vertical align contraint
        @IBOutlet weak var verticalConstraint: NSLayoutConstraint!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            verticalConstraint.constant = (myView.bounds.height + self.view.bounds.height)/2
        }
    
        override func viewDidAppear(animated: Bool) {
            super.viewDidAppear(animated)
            self.view.layoutIfNeeded()
            UIView.animateWithDuration(0.5) {
                self.verticalConstraint.constant = 0
                self.view.layoutIfNeeded()
            }
        }
    
    }
    

    Be careful about firstItem and secondItem order in the constraint. The above code assumes Superview is the firstItem:

    screenshot


    Alternative way is to define two constraints:

    • Center Y Alignment constraint (Superview.CenterY == View.CenterY) priority = 750
    • Vertical Space Constraint (SuperView.Top == View.Bottom) priority = 500

    screenshot

    And adjust the priority to determine which contraint should be adopted.

    class ViewController: UIViewController {
    
        //  vertical align contraint
        @IBOutlet weak var centerYConstraint: NSLayoutConstraint!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            centerYConstraint.priority = 250
        }
    
        override func viewDidAppear(animated: Bool) {
            super.viewDidAppear(animated)
            self.view.layoutIfNeeded()
            UIView.animateWithDuration(0.5) {
                self.centerYConstraint.priority = 750
                self.view.layoutIfNeeded()
            }
        }
    
    }
    

提交回复
热议问题