skip to Main Content

I have the following playground and can’t figure out why the ImageView width constraing is not being respected and it fills the remaining space on the StackView

import UIKit
import PlaygroundSupport

let view = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 800))

let imageView = UIView(frame: CGRect.zero)
imageView.backgroundColor = UIColor.red

imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.heightAnchor.constraint(equalToConstant: 40).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 40).isActive = true

let navBarHeaderStackView = UIStackView()
navBarHeaderStackView.distribution = .equalCentering
navBarHeaderStackView.alignment = .center
navBarHeaderStackView.axis = .horizontal
navBarHeaderStackView.addArrangedSubview(imageView)
//navBarHeaderStackView.addArrangedSubview(titlesStackView)

view.addSubview(navBarHeaderStackView)
navBarHeaderStackView.translatesAutoresizingMaskIntoConstraints = false

navBarHeaderStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 50).isActive = true
navBarHeaderStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 8).isActive = true
navBarHeaderStackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
navBarHeaderStackView.heightAnchor.constraint(equalToConstant: 60).isActive = true

navBarHeaderStackView.backgroundColor = UIColor.blue

PlaygroundPage.current.liveView = view

Result

2

Answers


  1. Because of this constraint

    navBarHeaderStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 8).isActive = true
    

    comment it and try

    Login or Signup to reply.
  2. Set trailingAnchor to lessThanOrEqualTo insted of equalTo.

    navBarHeaderStackView.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: 8).isActive = true
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search