AceLayout 提供了一个用于 Auto Layout 的 Swifty DSL。
some.top == another.leading
。view.translatesAutoresizingMaskIntoConstraints = false
constraint.isActive = true
调用你的 UIView
、UILayoutGuide
、NSView
或 NSLayoutGuide
的 autoLayout
方法,并使用一个闭包来描述 Auto Layout 约束。
view.autoLayout { item in
item.top.equal(to: anotherView, plus: 16) // to UIView
item.bottom.equalToSuperview() // to superview
item.leading.equal(to: layoutMarginsGuide) // to UILayoutGuide
item.trailing.equal(to: anotherView.centerXAnchor) // to NSLayoutAnchor
item.width.equal(to: 100) // to constant
item.height.equal(to: item.width) // to LayoutAnchor
}
在示例中,以下操作会自动完成
将 view.translatesAutoresizingMaskIntoConstraints
设置为 false
。
激活所有约束。
view.autoLayout { item in
item.top.greaterThanOrEqual(to: safeAreaLayoutGuide)
item.bottom.lessThanOrEqualToSuperview()
}
UILayoutPriority
和 NSLayoutConstraint.Priority
可用。
view.autoLayout { item in
item.center.equalToSuperview().priority(.required)
item.size.equal(toSquare: 100).priority(.defaultHigh)
}
你可以指定一个参数 activates
来确定是否立即激活约束。
let constraints = view.autoLayout(activates: false) { item in
item.edges.equal(to: anotherView)
}
// All constraints are not active.
assert(constraints.allSatisfy { !$0.isActive })
// You can activate them at any time.
NSLayoutConstraint.activate(constraints)
view.autoLayout { item in
item.center.equal(to: anotherView)
item.topLeading.equalToSuperview()
}
view.autoLayout { item in
item.size.equal(to: CGSize(width: 100, height: 200))
}
view.autoLayout { item in
item.leadingTrailing.equal(to: anotherView)
item.topBottom.equalToSuperview(insetBy: 16)
}
view.autoLayout { item in
item.edges.equalToSuperview(insetBy: 16)
}
leading
trailing
left
right
centerX
top
bottom
centerY
firstBaseline
lastBaseline
width
height
center
topLeading
topTrailing
topLeft
topRight
bottomLeading
bottomTrailing
bottomLeft
bottomRight
size
leadingTrailing
leftRight
topBottom
edges
要在 SwiftPM 项目中使用 AceLayout
库,请将以下行添加到你的 Package.swift
文件中的依赖项中
.package(url: "https://github.com/jrsaruo/AceLayout", from: "1.1.3"),
并将 AceLayout
添加为你目标的依赖项
.target(name: "<target>", dependencies: [
.product(name: "AceLayout", package: "AceLayout"),
// other dependencies
]),
最后,在你的源代码中添加 import AceLayout
。