【问题标题】:How to change bottom layout constraint in iOS, Swift如何在 iOS、Swift 中更改底部布局约束
【发布时间】:2015-11-12 07:10:34
【问题描述】:

我有 @IBOutlet 的滚动视图

@IBOutlet weak var mainScrollView: UIScrollView!

我想换个

"Bottom space to: Bottom Layout Guide" 

以编程方式约束。

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

我该怎么做?

【问题讨论】:

    标签: ios xcode swift storyboard nslayoutconstraint


    【解决方案1】:

    将约束设为IBOutlet of NSLayoutConstraint

    设置约束出口并通过以下方式更改constant值:

    self.sampleConstraint.constant = 20
    self.view.layoutIfNeeded()
    

    【讨论】:

    • 哪里最好改?
    【解决方案2】:

    如果您像这样以编程方式添加约束:

    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)
    

    那么你可以这样更新:

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

    如果你想用动画做到这一点,你可以这样做:

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

    希望对你有帮助。

    【讨论】:

    • 记得做 buttonPlay.translatesAutoresizingMaskIntoConstraints = false 并设置高度和宽度约束
    【解决方案3】:

    为您的约束创建一个IBOutlet

    @property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomContraint;
    

    当你需要改变它时:

    bottomContstraint.constant = //your value
    view.layoutIfNeeded()
    

    您也可以像这样为约束更改设置动画:

    bottomContstraint.constant = //your value
    
    UIView.animateWithDuration(0.5, animations: {
      self.view.layoutIfNeeded()
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 2021-04-30
      • 2012-11-24
      相关资源
      最近更新 更多