1. 程式人生 > >通過程式碼 新增 和 修改 NSLayoutConstraint

通過程式碼 新增 和 修改 NSLayoutConstraint

               

今天因為要弄一個瀑布流裡面item的動態載入,

所以考慮把裡面的一些空間的高度設成0從而實現“隱藏”效果

網上對這類修改是 關聯 NSLayoutConstraint

然後設定對應的constant

下面是網上的答案,但是注意了,要用父類layoutIfNeeded()來重新佈局

0 down vote

If you are adding constraint programatically like this:

var constraintButton = NSLayoutConstraint (item: buttonPlay,                                            attribute
: NSLayoutAttribute.Bottom,                                            relatedBy: NSLayoutRelation
.Equal,                                            toItem: self.view,                                            attribute: NSLayoutAttribute.Bottom,                                            multiplier: 1,                                           constant: 0)// Add the constraint to the viewself.view.addConstraint(constraintButton)

Then you can update it this way:

self.constraintButton.constant = 50self.view.layoutIfNeeded()

And if you want that with animation you can do it this way:

self.view.layoutIfNeeded()UIView.animateWithDuration(1, animations: {    self.constraintButton.constant = 50    self.view.layoutIfNeeded()})


0 down vote

If you are adding constraint programatically like this:

var constraintButton = NSLayoutConstraint (item: buttonPlay,                                            attribute: NSLayoutAttribute.Bottom,                                            relatedBy: NSLayoutRelation.Equal,                                            toItem: self.view,                                            attribute: NSLayoutAttribute.Bottom,                                            multiplier: 1,                                           constant: 0)// Add the constraint to the viewself.view.addConstraint(constraintButton)

Then you can update it this way:

self.constraintButton.constant = 50self.view.layoutIfNeeded()

And if you want that with animation you can do it this way:

self.view.layoutIfNeeded()UIView.animateWithDuration(1, animations: {    self.constraintButton.constant = 50    self.view.layoutIfNeeded()})
           

再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智慧的隊伍中來!https://blog.csdn.net/jiangjunshow