How do I remove restrictions from all subzones within my supervisor?
I have a UIView that contains multiple UIView subordinates that have their own constraints. How to remove subviews constraints?
//only removes the constraints on self.view
[self.view removeConstraints:self.view.constraints];
//I get warning: Incompatible pointer types sending 'NSArray *' to parameter of type 'NSLayoutConstraint'
[self.subview1 removeConstraints:self.subview1.constraints];
source to share
Try this code:
for (NSLayoutConstraint *constraint in self.view.constraints) {
if (constraint.firstItem == self.subview1 || constraint.secondItem == self.subview1) {
[self.view removeConstraint:constraint];
}
}
Basically, this repeats all constraints assigned self.view
and checks if self.subview1
the constraint is involved . If so, this constraint is stretched.
source to share
You must remove all constraints from the view and its subview. Therefore, create a UIView extension and then define the following method:
extension UIView {
func removeAllConstraints() {
self.removeConstraints(self.constraints)
for view in self.subviews {
view.removeAllConstraints()
}
}
}
then call the following:
self.view.removeAllConstraints()
As said, it's fast. This might help you.
source to share
I wrote an extension on UIView:
extension UIView{
func removeConstraintsFromAllEdges(of view: UIView){
for constraint in constraints{
if (constraint.firstItem.view == view || constraint.secondItem?.view == view){
removeConstraint(constraint)
}
}
}
func addConstraintsToAllEdges(of view: UIView){
let leading = leadingAnchor.constraint(equalTo: view.leadingAnchor)
let top = topAnchor.constraint(equalTo: view.topAnchor)
let trailing = trailingAnchor.constraint(equalTo: view.trailingAnchor)
let bottom = bottomAnchor.constraint(equalTo: view.bottomAnchor)
NSLayoutConstraint.activate([leading, top, trailing, bottom])
}
}
Interesting note: this secondItem
is an optional property NSLayoutConstraint
, firstItem
not optional. What for? Because sometimes you may need to constrain the height of the view to a constant value so that you don't see another view.
source to share