简体   繁体   中英

Setting Auto Layout constraints of IBOutlet in code

If I have a UILabel that is an IBOutlet, why can't I just set its Auto Layout constraints in code without also having to set at least one constraint in Storyboard?

For example, say I have an IBOutlet UILabel that has no constraints set in storyboard, and I try to center it in superview:

override func viewDidLoad() {
    super.viewDidLoad()
    self.label.setTranslatesAutoresizingMaskIntoConstraints(false)
    self.label.centerInSuperview()
}

Then I have a UIView extension for handling the auto layout code as follows:

extension UIView {

    func centerInSuperview() {
        self.centerVerticallyInSuperview()
        self.centerHorizontallyInSuperview()
    }

    func centerVerticallyInSuperview() {
        self.superview?.addConstraint(NSLayoutConstraint(
            item: self,
            attribute: NSLayoutAttribute.CenterY,
            relatedBy: NSLayoutRelation.Equal,
            toItem: self.superview,
            attribute: NSLayoutAttribute.CenterY,
            multiplier: 1,
            constant: 0))
    }

    func centerHorizontallyInSuperview() {
        self.superview?.addConstraint(NSLayoutConstraint(
            item: self,
            attribute: NSLayoutAttribute.CenterX,
            relatedBy: NSLayoutRelation.Equal,
            toItem: self.superview,
            attribute: NSLayoutAttribute.CenterX,
            multiplier: 1,
            constant: 0))
    }

}

The above code works fine if the UILabel is created from code:

var label = UILabel()
label.text = "Label"
self.view.addSubview(label)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
label.centerInSuperview()

But if the UILabel is an outlet with no constraints set in storyboard it doesn't work. Curiously if the outlet has one random constraint set in storyboard (like top space to superview), then it also works.

If a storyboard or NIB has auto layout enabled for it, Xcode will not allow a view to lack constraints. Select the view and bring up the Size inspector. You will see a note to the effect that "The selected views have no constraints. At build time, explicit left, top, width, and height constraints will be generated for the view."

In general, Xcode will provide constraints to eliminate ambiguity in the layout.

You can work around this by adding sufficient constraints to the view but marking them as placeholders (remove at build time). This will leave the view without constraints.

You could also add constraints, set up outlets to the constraints, and remove them programmatically before adding other constraints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM