Swift:尽管添加了元素,UIStackView的高度始终为0

问题描述

我有这个堆栈视图,它包含一个ImageView:

enter image description here

如果我打印它的高度,我总是得到0:

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

这是它的创建方式:

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
    
}

对此有什么解释吗?

解决方法

将任何视图添加为堆栈视图的arrangedSubview时,其.translatesAutoresizingMaskIntoConstraints属性将自动设置为`false。

因此,取决于您如何设置堆栈视图的“对齐方式”和“分布”属性,您可能需要向视图添加“宽度”和/或“高度”约束。

您显示的代码中有一些奇怪的设置,例如:

  • let movieImageViewWidth = 20.00 ...您真的希望它只有20点宽吗?
  • movieDetailsStackView!.distribution = .fillProportionally ...几乎可以肯定, 是您要分发的内容。从.fill开始,只有在未获得理想结果时才进行更改。
  • 您正在使用大量! ...“强制展开”是导致崩溃的原因。

但是,使用您现有的代码,添加以下行:

movieDetailsStackView = UIStackView(arrangedSubviews: arrangedSubviews)

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

看看您是否得到想要的结果。