AnchorPal
受到 SnapKit 启发的 AutoLayout 库。
安装
CocodPods
将此行添加到您的 Podfile 中
pod 'AnchorPal'
手动
将 AnchorPal.xcodeproj
添加到您的当前项目中。
使用
如果您熟悉 SnapKit,您已经知道如何使用 AnchorPal,只需进行一些小改动即可。
安装新的约束。
view.anc.installConstraints { the in
the.xEdges.equalToSuperview()
// with a optional parameter, you can easily refer to the layoutGuides of superview
the.yEdges.equalToSuperview(\.safeArea)
}
重新安装约束。
view.anc.reinstallConstraints { the in
the.height.equalTo(newValue)
}
不安装直接设置约束。
let constaints = view.anc.makeConstraints { the in
the.edges.equalToSuperview(\.safeArea)
}
// Activate them later
constraints.activate()
内嵌
注意:我们不使用 first.relationTo(second).inset(x)
格式,因为它含糊不清。
当我们说 first.>=(second).inset(x)
时,它可以是“第一项在x内嵌时值大于第二项”,也可以是“从第二项到第一项的内嵌大于x”。我们希望表达意图清晰。
view.anc.installConstraints { the in
the.edges.insetFromSuperview().equalTo(30)
}
// or
view.anc.installConstraints { the in
the.edges.insetFrom(otherView).greaterEqualTo(30)
}
设置动态约束常量。
view.anc.installConstraints { the in
the.width.equalTo { position -> CGFloat in
// return a CGFloat as the new constant
// position is the info about the current anchor which is calling this closure
return newWidth
}
}
// update constants later
view.anc.updateConstraintConstants()
自定义维度(iOS 10+、tvOS 10+、macOS 10.12+)
view1.anc.reinstallConstraints { the in
let space1 = the.trailing.spaceBefore(view2.anc.leading)
let space2 = the.bottom.spaceBefore(view3.anc.top)
space1.equalTo(space2)
}
系统间距(iOS 11+、tvOS 11+、macOS 11+)
// custom dimension to system spcaing
view1.anc.reinstallConstraints { the in
the.leading.spaceAfter(view2.anc.trailing).equalToSystemSpacing().multiply(2)
}
// or anchor to anchor
view1.anc.reinstallConstraints { the in
the.leading.equalToSystemSpacingAfter(view2.anc.trailing).multiply(2)
}
在静态函数中安装或创建约束。
// Sometimes you just don't want to bind these constraints to any view.
Anc.installConstraints {
view1.anc.edges.equalToSuperview(\.safeArea)
view2.anc.top.equalTo(view1.anc.bottom).plus(20)
}
在闭包外部安装或创建约束。
// make and install
view1.anc.edges.equalToSuperview(\.safeArea).active()
view2.anc.top.equalTo(view1.anc.bottom).plus(20).active()
// or just make
let constraint1 = view1.anc.edges.equalToSuperview(\.safeArea)
let constraint2 = view2.anc.top.equalTo(view1.anc.bottom).plus(20)
关于关系名称。
我们将 lessThanOrEqualTo
改为 lessEqualTo
,将 greaterThanOrEqualTo
改为 greaterEqualTo
,使代码更简洁,但仍然没有歧义。
结束语
AnchorPal 设计得灵活易读,希望您会喜欢它,如果不,请随时告诉我们。