Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Snapkit: Constrain multiple to margins

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?

like image 677
TRG Avatar asked Sep 08 '17 14:09

TRG


2 Answers

did you try something like this?

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

Edit after comment:

When you only want to constrain certain edges to the superview margin, you can do something like this.

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

or

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

or

subView.snp.makeConstraints { make in
    make.top.leading.equalTo(view.safeAreaLayoutGuide)
like image 123
JustinM Avatar answered Oct 12 '22 22:10

JustinM


One nice way to do this is to use UIView.layoutMarginsGuide:

childView.snp.makeConstraints { make in
    make.top.leading.bottom.equalTo(parentView.layoutMarginsGuide)
    make.trailing.equalTo(otherView.snp.leading).offset(-8.0)
}
like image 33
arsenius Avatar answered Oct 13 '22 00:10

arsenius