Pinnable Header Image

简介

Pinnable 提供了创建 NSLayoutConstraint 的便捷方法,而 NSLayoutConstraint 是使用 Auto Layout 的基础。 然而,标准的 UIKit API 没有提供足够的默认值,并且也可能导致令人沮丧的结果 - 例如,当你忘记设置 translatesAutoresizingMaskIntoConstraints 时。

Pinnable 引入了一个“单一”方法 - pin - 它提供了合理的默认值,在需要时禁用 translatesAutoresizingMaskIntoConstraints,并自动激活创建的约束。

这不是一个 DSL,没有“魔法”,也没有花哨的运算符重载。 因为我不太喜欢那些东西 :) 它只是比内置的 API 稍微方便一点。

安装

Pinnable 可作为一个 Swift Package 使用。 使用 Xcode GUI 添加它,或者将以下内容添加到您的 Package.swift

.package(url: "https://github.com/kylebshr/Pinnable", from: "0.0.3")

开始使用

导入 Pinnable 后,您会在 UIViewUILayoutGuideNSLayoutAnchorNSLayoutDimension 上找到新的 pin 方法。 它们中的大多数都相当具有自我描述性。 例如,要将一个视图的前导锚点约束到另一个视图的前导锚点,只需将它们 pin 在一起即可

firstView.leadingAnchor.pin(to: secondView.leadingAnchor)

// With a constant
firstView.leadingAnchor.pin(to: secondView.leadingAnchor, constant: 20)

// ...and a priority
firstView.leadingAnchor.pin(to: secondView.leadingAnchor, constant: 20, priority: .defaultLow)

或者,您可能想将第一个视图的所有边缘固定到第二个视图

firstView.pinEdges(to: secondView)

// With insets
firstView.pinEdges(to: secondView, insets: .init(top: 10, left: 20, bottom: 30, right: 20))

// ...or excluding the bottom edge
firstView.pinEdges([.top, .left, .right], to: secondView)

UIView(和 UILayoutGuide)上可用的方法用于为多个锚点创建约束(例如,pinEdges 可以固定多个边缘,pinSize 约束宽度和高度尺寸)。

所有 pin 方法都会返回已创建的约束,因此您可以引用它们并随意修改它们。 或者可以随意忽略它们。 他们不在意。