AnchorChain 0.6.0

AnchorChain 0.6.0

André Gillfrost 维护。



  • 作者:
  • André Gillfrost

AnchorChain

Build Status codecov Version Platform License

围绕NSLayoutAnchor系统的一个包装器,由以下设计目标/权衡所驱动

  • 表达方式的便捷性应与其使用的频率成比例。换句话说:将视图约束到其父视图的边缘应该是微不足道的,确实如此: view.anchor()

  • 使用时的直观性。将视图的顶部约束到另一个视图的底部应该表达为: view.anchor(.top, to: .bottom, of: anotherView),确实如此。

    • 权衡:自动补全将有限,因为锚定方法被高度重载。
  • 链式可促进更具声明性的布局代码。在声明点约束视图应像这样简单:let view = UIView().anchoring(.width, to: 100),确实如此。

  • 对视图层次结构稍微主动一些。当将锚点约束到匹配另一个视图时,例如这: UIActivityIndicatorView().anchor(.centerX, .centerY, to: view),可以假定接收者(如果没有父视图)应添加为其他视图的子视图,确实如此。

    • 权衡:这是一个相当严重的副作用,但考虑到在两个没有共同祖先的视图之间创建(激活)约束本身就是程序员的错误,所以这有意义。

使用

匹配属性

...到 superview

// All edges
view.anchor()

// Some edges
view.anchor(.top, .left, .right)

// To safe area
view.anchor(to: .safeArea)

// With insets
view.anchor(with: UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20))

// Save constraint for later use
let constraint = view.anchor(.top)

// Inactive constraint
let constraint = view.anchor(.top, isActive: false)

// Prioritized like a complete refactoring in your backlog
view.anchor(.top, priority: .defaultLow)

...到其他视图

// All edges
view.anchor(to: otherView)

// Some edges
view.anchor(.top, .left, .right, to: otherView)

// To safe area
view.anchor(to: .safeArea, of: otherView)

// With insets
view.anchor(to: otherView, with: UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20))

// Save constraint for later use
let constraint = view.anchor(.top, to: otherView)

// Inactive constraint
let constraint = view.anchor(.top, to: otherView, isActive: false)

// With priority
view.anchor(.top, to: otherView, priority: .defaultLow)

尺寸

view.anchor(.width, to: 100)
view.anchor(.height, to: 100)
// or simply
view.anchor(.size, to: 100)

对齐

// Top to bottom of other view
view.anchor(.top, to: .bottom, of: otherView)

// Left greater than or equal to right of other view
view.anchor(.left, .greaterThanOrEqual, to: .right, of: otherView)

要求

iOS 11

XCode 10

Swift 4.2

安装

CocoaPods

使用CocoaPods将AnchorChain集成到XCode项目中,请在Podfile中添加以下内容

pod 'AnchorChain'

许可证

AnchorChain 可在 MIT 许可证下使用。有关更多信息,请参阅 LICENSE 文件。