如何检查视图中是否已存在约束?
How to check if a constraint already exists inside a view?
我正在为我的 tableView 和其中的每个单元格使用自动布局,我以编程方式创建了一些约束。
为了避免每次都删除所有约束,我想知道是否有循环view.constraints()
的方法,如果有H:|-view-|
这样的约束,我删除它。
可能吗?
您需要使用变量(或数组)来保存与您想要的相匹配的约束,然后循环 view.constraints() 以删除它们。当您使用视觉格式时,您创建的任何内容都会转换为多个约束。
另一种方法是遍历约束并检查约束属性(例如 firstItem 和 secondItem、关系等)以匹配您想要的内容。
无需循环约束。这应该有效:
toRemove = NSLayoutConstraint.constraints(withVisualFormat: "H:|-view-|",
options: [],
metrics: nil,
views: ["view": yourView])
viewWithConstraints.removeConstraints(toRemove)
以下是我检查控件是否已经具有宽度或高度约束的方法 (Swift 5.1):
debugPrint(btn.constraints.contains(where: { (item) -> Bool in
return item.firstAttribute.rawValue == NSLayoutConstraint.Attribute.width.rawValue;
}))
debugPrint(btn.constraints.contains(where: { (item) -> Bool in
return item.firstAttribute.rawValue == NSLayoutConstraint.Attribute.height.rawValue;
}))
我正在为我的 tableView 和其中的每个单元格使用自动布局,我以编程方式创建了一些约束。
为了避免每次都删除所有约束,我想知道是否有循环view.constraints()
的方法,如果有H:|-view-|
这样的约束,我删除它。
可能吗?
您需要使用变量(或数组)来保存与您想要的相匹配的约束,然后循环 view.constraints() 以删除它们。当您使用视觉格式时,您创建的任何内容都会转换为多个约束。
另一种方法是遍历约束并检查约束属性(例如 firstItem 和 secondItem、关系等)以匹配您想要的内容。
无需循环约束。这应该有效:
toRemove = NSLayoutConstraint.constraints(withVisualFormat: "H:|-view-|",
options: [],
metrics: nil,
views: ["view": yourView])
viewWithConstraints.removeConstraints(toRemove)
以下是我检查控件是否已经具有宽度或高度约束的方法 (Swift 5.1):
debugPrint(btn.constraints.contains(where: { (item) -> Bool in
return item.firstAttribute.rawValue == NSLayoutConstraint.Attribute.width.rawValue;
}))
debugPrint(btn.constraints.contains(where: { (item) -> Bool in
return item.firstAttribute.rawValue == NSLayoutConstraint.Attribute.height.rawValue;
}))