2

I have this stack view, it contains one ImageView:
enter image description here If I print its height, I always get 0:

  print("movieDetailsStackView!.bounds.height: ",movieDetailsStackView!.bounds.height ) // 0
    print("movieDetailsStackView!.frame.height: ",movieDetailsStackView!.frame.height ) // 0

This is how it's created:

func createMovieDetailsStackView () {
    /******************/
    // Add movie image
    /*****************/
    let movieImageViewHeight = 300.00
    let movieImageViewWidth = 20.00
    movieImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: movieImageViewWidth, height: movieImageViewHeight));
    movieImageView!.layer.borderWidth = 10
    movieImageView!.layer.borderColor = UIColor.red.cgColor
    /******************/
    var arrangedSubviews = [UIView]()
    arrangedSubviews.append(movieImageView!)
    
    movieDetailsStackView = UIStackView(arrangedSubviews: arrangedSubviews)
    
    movieDetailsStackView!.translatesAutoresizingMaskIntoConstraints = false
    movieDetailsStackView!.distribution = .fillProportionally
    movieDetailsStackView!.axis = .horizontal
    movieDetailsStackView!.spacing = 8

    self.view.addSubview(movieDetailsStackView!)

    movieDetailsStackView!.topAnchor.constraint(equalTo: self.view.topAnchor, constant:70).isActive = true
    movieDetailsStackView!.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 0).isActive = true
    movieDetailsStackView!.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: 0).isActive = true
    
}

Is there any explanation for this?

AG_HIHI
  • 1,705
  • 5
  • 27
  • 69
  • Have you tried adding a height constraint to the stack view as well? one that is equal to the movieImageViewHeight – Alan S Oct 28 '20 at 10:23

1 Answers1

1

When you add any view as an arrangedSubview of a stack view, its .translatesAutoresizingMaskIntoConstraints property is automatically set to `false.

So, depending on how you have your stack view's Alignment and Distribution properties set, you may need to add Width and/or Height constraints to the view.

You have some odd settings in the code you've shown, for example:

  • let movieImageViewWidth = 20.00 ... do you really want it to be only 20-pts wide?
  • movieDetailsStackView!.distribution = .fillProportionally ... that is almost certainly NOT what you want for distribution. Start with .fill and only change that if you're not getting the desired result.
  • you're using a lot of ! ... "force unwrapping" is a recipe for crashes.

However, with your existing code, add this line:

movieDetailsStackView = UIStackView(arrangedSubviews: arrangedSubviews)

// add this line here
movieImageView?.heightAnchor.constraint(equalToConstant: CGFloat(movieImageViewHeight)).isActive = true

and see if you get your desired result.

DonMag
  • 69,424
  • 5
  • 50
  • 86