如何在 iOS、Swift 中更改底部布局约束
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32087809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change bottom layout constraint in iOS, Swift
提问by Joon. P
I have scroll view as @IBOutlet
我有滚动视图@IBOutlet
@IBOutlet weak var mainScrollView: UIScrollView!
I want to change the
我想改变
"Bottom space to: Bottom Layout Guide"
constraint programmatically.
以编程方式约束。
First Item : Bottom Layout Guide.Top
Relation : Equal
Second Item: Scroll View.Bottom
Constant: 0 -> 50 // (I want to change this programmatically)
Priority: 1000
Multiplier: 1
How can I do this?
我怎样才能做到这一点?
回答by Ashish Kakkad
Take the constraint as IBOutlet
of NSLayoutConstraint
.
以约束为IBOutlet
的NSLayoutConstraint
。
Set the constraint outlets and change constant
value by :
设置约束出口并constant
通过以下方式更改值:
self.sampleConstraint.constant = 20
self.view.layoutIfNeeded()
回答by Dharmesh Kheni
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 view
self.view.addConstraint(constraintButton)
Then you can update it this way:
然后你可以这样更新它:
self.constraintButton.constant = 50
self.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()
})
Hope it helps.
希望能帮助到你。
回答by Juri Noga
Create an IBOutlet
for your constraint:
IBOutlet
为您的约束创建一个:
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomContraint;
And when you need to change it call:
当您需要更改它时,请调用:
bottomContstraint.constant = //your value
view.layoutIfNeeded()
Also you can animate constraint change like that:
您也可以像这样为约束更改设置动画:
bottomContstraint.constant = //your value
UIView.animateWithDuration(0.5, animations: {
self.view.layoutIfNeeded()
})