如何从我的superview中的所有子视图中删除约束?

时间:2015-01-09 21:11:02

标签: ios objective-c uiview nslayoutconstraint

我有一个包含多个UIView子视图的UIView,它们有自己的约束。如何删除子视图'约束

//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];

4 个答案:

答案 0 :(得分:9)

试试这段代码:

for (NSLayoutConstraint *constraint in self.view.constraints) {
    if (constraint.firstItem == self.subview1 || constraint.secondItem == self.subview1) {
        [self.view removeConstraint:constraint];
    }
}

基本上,这会迭代分配给self.view的所有约束,并检查约束中是否包含self.subview1。如果是这样,那个约束就被拉了。

答案 1 :(得分:3)

您必须删除视图及其子视图的所有约束。因此,创建UIView的扩展,然后定义以下方法:

extension UIView {
    func removeAllConstraints() {
        self.removeConstraints(self.constraints)
        for view in self.subviews {
            view.removeAllConstraints()
        }
    }
}

然后调用以下内容:

self.view.removeAllConstraints()

稍后回答,这很快。这可能会对你有帮助。

答案 2 :(得分:0)

我在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])
    }
}

有趣的提示是secondItemNSLayoutConstraint的可选属性,而firstItem是非可选的。为什么?因为有时您可能需要将视图的高度约束为常量值,因此您不会涉及其他视图。

答案 3 :(得分:0)

我接受了@ Honey的回答,并将其修改为有效,因此视图可以消除与其超级视图相关的约束。

extension UIView{

    func removeConstraintsFromAllEdges(){

        if let superview = superview {

            for constraint in superview.constraints{

                if let firstItem = constraint.firstItem, firstItem === self {
                    superview.removeConstraint(constraint)
                }

                if let secondItem = constraint.secondItem, secondItem === self {
                    superview.removeConstraint(constraint)
                }

            }

        }

    }

}