Search code examples
swiftxcodemacos-mojave

How do I resolve Failed to render and update auto layout status? after adding constraint to custom control in xcode 10.2.1


I have the following custom control:

import UIKit
import os.log

@IBDesignable class LocationControl: UIStackView {
    @IBInspectable var nameSize: CGSize = CGSize(width: 100.0, height: 21.0) {
        didSet {
            setupLabels()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLabels()
    }

    required init(coder: NSCoder) {
        super.init(coder: coder)
        setupLabels()
    }

    private func setupLabels() {
        // Create the labels
        let nameLabel = UILabel()
        nameLabel.text = "Name"
        nameLabel.backgroundColor = UIColor.red

        let textLabel = UILabel()
        textLabel.text = "Text"
        textLabel.backgroundColor = UIColor.green

        // Add constraints
        let margins = self.layoutMarginsGuide

        nameLabel.translatesAutoresizingMaskIntoConstraints = false
        nameLabel.heightAnchor.constraint(equalToConstant: nameSize.height).isActive = true
        nameLabel.widthAnchor.constraint(equalToConstant: nameSize.width).isActive = true
//        nameLabel.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true

        self.addSubview(nameLabel)
        self.addSubview(textLabel)
    }
}

This code works without error (but not as desired). If I uncomment the line

//        nameLabel.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true

And then switch to Main.storyboard in the Standard Editor, I get the following error:

file:///Users/tim.daley/AixNPanes/iOS/location/location/Base.lproj/Main.storyboard: error: IB Designables: Failed to render and update auto layout status for UIViewController (29D-8H-aV6): The agent threw an exception.

I'm running Xcode Version 10.2.1 (10E1001) on macOS Mojave 10.14.5


Solution

  • You may need to add the views before the constraints

    self.addSubview(nameLabel)
    self.addSubview(textLabel)
    
    nameLabel.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
       nameLabel.heightAnchor.constraint(equalToConstant: nameSize.height),
       nameLabel.widthAnchor.constraint(equalToConstant: nameSize.width),
       nameLabel.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
    ])