Reputation: 9527
I have this code, that changle constraint based on visibility of element:
if (self.collectionView.isHidden){
controller.view.bottomAnchor.constraint(equalTo: self.collectionView.topAnchor).isActive = false
controller.view.bottomAnchor.constraint(equalTo: self.view2.topAnchor).isActive = true
}
else {
controller.view.bottomAnchor.constraint(equalTo: self.collectionView.topAnchor).isActive = true
controller.view.bottomAnchor.constraint(equalTo: self.view2.topAnchor).isActive = false
}
If I do this after collectionView.isHidden
is set to true, it works. However, after I set collectionView.isHidden = true
and call this code, it no longer works and controller.view
is still attached to the top of view2.
There is also an height constraint attached to collectionView
ant ist values is 50.
I also have tried manually setting collectionView.frame.size.height = 50
(or some other default value) because without this, height of collectionView.frame.size.height
is zero. But not works. I have tried call collectionView.updateConstraints()
, but it has no effect either.
Upvotes: 0
Views: 189
Reputation: 169
So, I think you are setting a new constraint every time you call the function, you are not really removing the previous one.
Usually when I need this kind of logic I keep a reference to the constraint so that I can activate/deactivate it later, like this:
var controllerBottomAnchor: NSLayoutConstraint?
Then I assign it like so:
controllerBottomAnchor = controller.view.bottomAnchor.constraint(equalTo: self.collectionView.topAnchor)
controllerBottomAnchor?.isActive = true
Once I need to change it I just use the reference:
controllerBottomAnchor?.isActive = false
I typically use it for width and height anchors.
Upvotes: 3