Home > Net >  UILabel position not updating even after changing constraints on button click
UILabel position not updating even after changing constraints on button click

Time:12-17

I am trying to change the constraints of a UILabel to 30 pixels down so I'm changing it like below:

The initial constraints are:

testLabel.topAnchor.constraint(equalTo: fastestInfoText.bottomAnchor,constant: 5).isActive = true

The button functionality:

@objc func infoIcon3Pressed(sender: UIButton){  
    fastestInfoText.isHidden = !fastestInfoText.isHidden
    testLabel.topAnchor.constraint(equalTo: fastestInfoText.bottomAnchor,constant: 30).isActive = true
}

But still the UILabel is not changing its position to up or down.

I was trying to change constraints after button is clicked.

CodePudding user response:

You're actually creating 2 constraints and activating them both.

Instead make constraint as global variable, and update the constant value when user taps on Button.

lazy var testLabelTopConstraint = testLabel.topAnchor.constraint(equalTo: fastestInfoText.bottomAnchor, constant: 5);

// Activate constraint in view didload.
testLabelTopConstraint.isActive = true

@objc func infoIcon3Pressed(sender: UIButton){
  fastestInfoText.isHidden = !fastestInfoText.isHidden
  testLabelTopConstraint.constant = 30
}
  • Related