I\'ve been looking for a lot of snippets in the net and I still can\'t find the answer to my problem. My question is I have a scrollView(SV) and I want to add a button insid
Here's a more functional approach in Swift 3+ with a precondition instead of a print (which can perish easily in the console). This one will report programmer errors as failed builds.
Add this extension to your project:
extension UIView {
/// Adds constraints to the superview so that this view has same size and position.
/// Note: This fails the build if the `superview` is `nil` – add it as a subview before calling this.
func bindEdgesToSuperview() {
guard let superview = superview else {
preconditionFailure("`superview` was nil – call `addSubview(view: UIView)` before calling `bindEdgesToSuperview()` to fix this.")
}
translatesAutoresizingMaskIntoConstraints = false
["H:|-0-[subview]-0-|", "V:|-0-[subview]-0-|"].forEach { visualFormat in
superview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: visualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["subview": self]))
}
}
}
Now simply call it like this:
// after adding as a subview, e.g. `view.addSubview(subview)`
subview.bindEdgesToSuperview()
Note that the above method is already integrated into my HandyUIKit framework which also adds some more handy UI helpers into your project.
If you work a lot with programmatic constraints in your project then I recommend you to checkout SnapKit. It makes working with constraints a lot easier and less error-prone.
Follow the installation instructions in the docs to include SnapKit into your project. Then import it at the top of your Swift file:
import SnapKit
Now you can achieve the same thing with just this:
subview.snp.makeConstraints { make in
make.edges.equalToSuperview()
}