How to update the constant height constraint of a UIView programmatically?

后端 未结 9 2250
执笔经年
执笔经年 2020-11-27 11:16

I have a UIView and I set the constraints using Xcode Interface Builder.

Now I need to update that UIView instance\'s height constant progra

相关标签:
9条回答
  • 2020-11-27 11:52

    To update a layout constraint you only need to update the constant property and call layoutIfNeeded after.

    myConstraint.constant = newValue
    myView.layoutIfNeeded()
    
    0 讨论(0)
  • 2020-11-27 11:55

    If the above method does not work then make sure you update it in Dispatch.main.async{} block. You do not need to call layoutIfNeeded() method then.

    0 讨论(0)
  • 2020-11-27 12:00

    If you have a view with multiple constrains, a much easier way without having to create multiple outlets would be:

    In interface builder, give each constraint you wish to modify an identifier:

    Then in code you can modify multiple constraints like so:

    for constraint in self.view.constraints {
        if constraint.identifier == "myConstraint" {
           constraint.constant = 50
        }
    }
    myView.layoutIfNeeded()
    

    You can give multiple constrains the same identifier thus allowing you to group together constrains and modify all at once.

    0 讨论(0)
  • 2020-11-27 12:03

    Drag the constraint into your VC as an IBOutlet. Then you can change its associated value (and other properties; check the documentation):

    @IBOutlet myConstraint : NSLayoutConstraint!
    @IBOutlet myView : UIView!
    
    func updateConstraints() {
        // You should handle UI updates on the main queue, whenever possible
        DispatchQueue.main.async {
            self.myConstraint.constant = 10
            self.myView.layoutIfNeeded()
        }
    }
    
    0 讨论(0)
  • 2020-11-27 12:06
    Create an IBOutlet of NSLayoutConstraint of yourView and update the constant value accordingly the condition specifies.
    
    //Connect them from Interface 
    @IBOutlet viewHeight: NSLayoutConstraint! 
    @IBOutlet view: UIView!
    
    private func updateViewHeight(height:Int){
       guard let aView = view, aViewHeight = viewHeight else{
          return
       }
       aViewHeight.constant = height
       aView.layoutIfNeeded()
    }
    
    0 讨论(0)
  • You can update your constraint with a smooth animation if you want, see the chunk of code below:

    heightOrWidthConstraint.constant = 100
    UIView.animate(withDuration: animateTime, animations:{
    self.view.layoutIfNeeded()
    })
    
    0 讨论(0)
提交回复
热议问题