The problem is that you are adding the constraint to stackView rather than containerView.

The documentation for addConstraint states

The constraint to be added to the view. The constraint may only reference the view itself or its subviews.

containerView is the super view of stackView, not a sub view.

If you change your code to add the constraint to the containerView it will run

containerView.addConstraint(.init(item: stackView, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1, constant: 0))
containerView.addConstraint(.init(item: stackView, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1, constant: 0))

You will probably want to add a trailing and a bottom constraint so that the stack view fills the whole container view. You will, of course, also need to add an arrangedSubview so that there is actually some content in the stack view.

It is generally simpler to add constraints by referencing layout guides rather than this older, more verbose, approach:

import UIKit
import PlaygroundSupport

let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
containerView.backgroundColor = UIColor.white

let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(stackView)

stackView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true


let label = UILabel()
label.text = "Hello world"
label.textColor = .black
stackView.addArrangedSubview(label)
PlaygroundPage.current.liveView = containerView

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top