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?
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)
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With