测试已测试 | ✗ |
Lang语言 | SwiftSwift |
许可证 | MIT |
Released最新发布 | 2016年11月 |
SwiftSwift版本 | 3.0 |
SPM支持SPM | ✗ |
由Garrit Schaap维护。
Swift中AutoLayout的助手
您知道问题:您只想在代码中设置一个NSLayoutConstraint,最终却得到这样
addConstraint(NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0))
不是更好写成类似于这样更swift风格的,更易读的代码吗?
view.LA.setTop.addToSuperview()
有了Lane Assist,您可以这样做!只需将Lane Assist添加到您的项目中,您就完成了。Lane Assist不是您必须学习的AutoLayout之上的DSL,它只是通过一些简单的函数调用创建基本的NSLayoutConstraints。方法链使使用更加舒适。
您可以将LaneAssist/LaneAssist.swift
文件手动复制并添加到您的项目中使用。如果您的项目针对iOS 7,这是唯一可行的方式。
setWidth
setHeight
setTop
setBottom
setLeft
setRight
setCenterX
setCenterY
setBaseline
这些变量是可选的。如果您还没有将视图添加到视图层次结构中,它将返回nil!
equalTo()
greaterThanOrEqual()
lessThanOrEqual()
toBaseline()
toLeft()
toRight()
toTop()
toBottom()
toCenterX()
toCenterY()
toWidth()
toHeight()
toBaseline()
toCenterXWithinMargins()
toCenterYWithinMargins()
toFirstBaseline()
toLeading()
toLeadingMargin()
toLeftMargin()
toRightMargin()
toTopMargin()
toBottomMargin()
toTrailing()
toTrailingMargin()
ofView(view: UIView)
ofSelf()
withMultiplier(multiplier: CGFloat)
withConstant(constant: CGFloat)
setFixed(constant: CGFloat)
withPriority(priority: UILayoutPriority)
addToSuperview()
addToView(view: UIView)
addToSelf()
您可以轻松地按顺序链接所有属性。首先从一个视图开始,获取Lane Assist对象view.LA
,这将设置视图的translatesAutoresizingMaskIntoConstraints
为false。然后选择要设置的初始值,例如顶部view.LA.setTop
,现在您可以轻松地链接所有可用的方法,例如view.LA.setTop.toBottom().ofView(otherView).withConstant(10).withPriority(42).addToSuperview()
。
放置视图水平居中,距离顶部100px,宽度与父视图相同,高度与视图宽度相同的常用NSLayoutConstraint代码
addConstraint(NSLayoutConstraint(item: view, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 100))
addConstraint(NSLayoutConstraint(item: view, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: view, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 1, constant: 0))
使用Lane Assist的相同代码
view.LA.setCenterX.addToSuperview()
view.LA.setTop.withConstant(100).addToSuperview()
view.LA.setWidth.addToSuperview()
view.LA.setHeight.toWidth().ofSelf().addToSuperview()
要保留约束(例如如果您想对其进行动画处理),只需将其分配给变量。例如,我们要动画顶部约束
let topConstraint = view.LA.setTop.withConstant(100).addToSuperview()
self.layoutIfNeeded()
UIView.animateWithDuration(2, animations: { () -> Void in
self.topConstraint.constant = 200
self.layoutIfNeeded()
})
⚠️ 默认情况下,如果使用Lane Assist,则Lane Assist将您的视图的translatesAutoresizingMaskIntoConstraints
设置为false
。
我目前在实际项目中使用了Lane Assist。如果您在项目中使用Lane Assist,我很乐意听到您的想法和建议。您可以通过Twitter联系我。