Width and Height Equal to its superView using autolayout programmatically?

前端 未结 11 1483
后悔当初
后悔当初 2020-12-07 09:09

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

11条回答
  •  余生分开走
    2020-12-07 10:07

    Approach #1: Via UIView Extension

    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.


    Approach #2: Using a Framework

    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()
    }
    

提交回复
热议问题