Approach # 1: UIView Extension
Here's a more functional Swift 3 approach with a precondition instead of print (which can easily die in the console). This 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 just name it like this:
Please note that the above method is already integrated into my HandyUIKit , which also adds some more convenient UIs to your project.
Approach # 2: Using Structure
If you work a lot with software restrictions in your project, I recommend that you check SnapKit.This makes working with restrictions much easier and less error prone.
Follow the instructions in the docs to include SnapKit in your project. Then import to the top of your Swift file:
import SnapKit
Now you can achieve the same goal with just this:
subview.snp.makeConstraints { make in make.edges.equalToSuperview() }
Dschee Dec 30 '16 at 9:24 2016-12-30 09:24
source share