AceLayout

AceLayout 提供了一个用于 Auto Layout 的 Swifty DSL。

Test codecov

要求

特性

用法

基础

构建约束

调用你的 UIViewUILayoutGuideNSViewNSLayoutGuideautoLayout 方法,并使用一个闭包来描述 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.autoLayout { item in
    item.top.greaterThanOrEqual(to: safeAreaLayoutGuide)
    item.bottom.lessThanOrEqualToSuperview()
}

优先级

UILayoutPriorityNSLayoutConstraint.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)
}

可用的锚点

X 轴

Y 轴

基线(仅限 UIView / NSView

尺寸

尺寸

水平边缘

垂直边缘

边缘

在你的项目中使用 AceLayout

要在 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