有SnapKit了,为什么还要自己再写一个?
我觉得除了SnapKit的实现方式,应该还有更加简洁的实现,而且我不太喜欢老用闭包,这样使得UI的代码很长。
于是就有了Driftwood布局框架。
快速上手
比如设置一个相对于superview
的上下左右位置关系:
let box = UIView()
box.translatesAutoresizingMaskIntoConstraints = false
superview.addSubview(box)
box.dw.make.left(10).top(20).width(20).height(10)
其中dw
是访问Driftwood
相关方法的入口。
注意:请确保任何用到Driftwood的
View
都设置了translatesAutoresizingMaskIntoConstraints
为false
Constant参数
constant
参数与约束中的constant
意思是一样的。
box.dw.make.centerX(0).centerY(0).width(20).height(10)
Attribute参数
用Attribute
给view
指定它的位置关系。比如:view1
在view2
底部,距离10pt
:
view1.dw.make.top(10, to: view2.dw.bottom)
View
的更多位置关系见下表:
AttributeX |
NSLayoutAttribute |
---|---|
view.dw.left |
NSLayoutAttribute.left |
view.dw.right |
NSLayoutAttribute.right |
view.dw.leading |
NSLayoutAttribute.leading |
view.dw.trailing |
NSLayoutAttribute.trailing |
view.dw.centerX |
NSLayoutAttribute.centerX |
view.dw.leftMargin |
NSLayoutAttribute.leftMargin |
view.dw.rightMargin |
NSLayoutAttribute.rightMargin |
view.dw.leadingMargin |
NSLayoutAttribute.leadingMargin |
view.dw.trailingMargin |
NSLayoutAttribute.trailingMargin |
view.dw.centerXWithinMargins |
NSLayoutAttribute.centerXWithinMargins |
AttributeY |
NSLayoutAttribute |
---|---|
view.dw.top |
NSLayoutAttribute.top |
view.dw.bottom |
NSLayoutAttribute.bottom |
view.dw.centerY |
NSLayoutAttribute.centerY |
view.dw.lastBaseline |
NSLayoutAttribute.lastBaseline |
view.dw.firstBaseline |
NSLayoutAttribute.firstBaseline |
view.dw.topMargin |
NSLayoutAttribute.topMargin |
view.dw.bottomMargin |
NSLayoutAttribute.bottomMargin |
view.dw.centerYWithinMargins |
NSLayoutAttribute.centerYWithinMargins |
AttributeSize |
NSLayoutAttribute |
---|---|
view.dw.width |
NSLayoutAttribute.width |
view.dw.height |
NSLayoutAttribute.height |
Relation 和 Priority参数
给约束设置Relation和Priority参数,这俩参数与约束中的意思相同。
view.dw.make.width(100, by: .greaterThanOrEqual, priority: .required)
dw.make方法
使用dw.make
来设置约束。如果重复设置则会在运行时给出错误提示。
dw.update方法
使用dw.update
来更新约束。如果要更新的约束不存在则在运行时给出错误提示。
view1.dw.update.top(200)
view2.dw.update.left(100, priority: .required)
dw.remake
dw.remake
与dw.make
相似,但会先移除之前所有通过Driftwood设置的约束。
view.dw.remake.left(20).top(30).width(20).height(10)
dw.remove
使用dw.remove
移除之前通过Driftwood设置的约束。
view.dw.remove.left().top()
LayoutGuide
Driftwood支持LayoutGuide
与View
的组合使用,用法与View
的形式相同。
比如,设置View
相对于LayoutGuide
的位置关系:
let guide = UILayoutGuide()
superview.addLayoutGuide(guide)
guide.dw.make.left(10).top(64).right(-20).height(10).width(10)
let box = UIView()
box.translatesAutoresizingMaskIntoConstraints = false
superview.addSubview(box)
box.dw.make.top(0, to: guide.dw.bottom).left(0).right(0).height(10)
GitHub
Driftwood框架连接,喜欢的话给颗Star,能提提意见就更好啦!
网友评论