Snapkit: Constrain multiple to margins

时间:2017-09-08 14:52:27

标签: swift swift3 autolayout snapkit

I'm using Snapkit to simplify my autolayout code, however one scenario seems to popup very regularly, which i'm wondering if there's a way which involves less code.

So let's say that I need to pin the edges of a UIView to it's superview margins, we might do something like this:

subView.snp.makeConstraints { make in
    make.top.equalTo(parentView.snp.topMargin)
    make.bottom.equalTo(parentView.snp.bottomMargin)
    make.left.equalTo(parentView.snp.leftMargin)
    make.right.equalTo(parentView.snp.rightMargin)
}

This essentially results in the subview filling the parent view, except for a small amount of padding as defined by the parent views layout margins.I'm sure some variation of this is pretty common.

This seems overly verbose for this library. It has some really nice helper methods such as these

make.edges.equalToSuperview()
make.top.left.right.equalToSuperview()

What I haven't managed to find in their documentation however is how to do the two above helper methods, in relation to the margins.

What i'm looking for (if it exists) is something akin to:

make.edges.equalToSuperview().withMargins()
make.top.left.right.equalToSuperview().withMargins()
make.top.left.right.equalTo(someview).withMargins()

So, is there a way of doing this other than the very verbose way? Am I missing something in the documentation or maybe this could be added by extension?

2 个答案:

答案 0 :(得分:7)

你试过这样的事吗?

subView.snp.makeConstraints { make in
    make.edges.equalTo(view.snp.margins)
}

评论后编辑:

如果您只想将某些边缘约束到超视图边距,则可以执行以下操作。

subView.snp.makeConstraints { make in
    make.top.leading.equalTo(view).inset(view.layoutMargins)
}

subView.snp.makeConstraints { make in
    make.top.leading.equalTo(view.layoutMarginsGuide)

subView.snp.makeConstraints { make in
    make.top.leading.equalTo(view.safeAreaLayoutGuide)

答案 1 :(得分:1)

一种不错的方法是使用UIView.layoutMarginsGuide

childView.snp.makeConstraints { make in
    make.top.leading.bottom.equalTo(parentView.layoutMarginsGuide)
    make.trailing.equalTo(otherView.snp.leading).offset(-8.0)
}