获取视图约束

Iss*_*toz 1 ios swift

如何获取 UIView 的前导、尾随、顶部和底部约束,如截图所示

在此处输入图片说明

Aam*_*irR 5

为约束设置标识符更好更容易,如下面的屏幕截图所示,并使用以下

if let topConstraint = button.constraints.first(where: { $0.identifier == "topConstraint" }) {
    ... use topConstraint
}
Run Code Online (Sandbox Code Playgroud)

其它的办法:

if let topConstraint = button.constraints.first(where: { ($0.firstAttribute == .top && $0.firstItem === button) || ($0.secondAttribute == .top && $0.secondItem === button) }) {
    ... use topConstraint
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


小智 5

你可以用 3 种方式做到

  1. 带属性
{view}.constraints.filter { $0.firstAttribute == .leading }
Run Code Online (Sandbox Code Playgroud)
  1. 使用 Idenetifier,您可以从故事板中为约束提供标识符并获得如下
{view}.constraints.filter { $0.identifier == "your identifier" }
Run Code Online (Sandbox Code Playgroud)
  1. 您在页面中设置约束的出口