简体   繁体   English

UIStackView调整子视图的高度

[英]UIStackView adjust height to subviews

I want the UIStackView to resize to fit their subviews (UIImageView and UILabel in this case) 我希望UIStackView调整大小以适应他们的子视图(在这种情况下为UIImageView和UILabel)

    let headerView = UIStackView()
    headerView.axis = .vertical
    headerView.alignment  = .center
    headerView.distribution = .equalSpacing
    headerView.spacing = 10

    let headerImage = UIImageView(...)
    headerImage.contentMode = .scaleAspectFill
    headerImage.clipsToBounds = true
    headerImage.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: tableView.frame.width / 1.618)

    let desciptionView = UILabel()
    desciptionView.text = "Some very long text wrapping multiple lines..."
    desciptionView.numberOfLines = 0
    desciptionView.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)

    headerView.addArrangedSubview(headerImage)
    headerView.addArrangedSubview(desciptionView)

    print(headerView.bounds) // always 0,0,0,0
    print(headerView.frame) // always 0,0,0,0

    tableView.tableHeaderView = headerView

(in this code height and width are 0) (在此代码中高度和宽度均为0)

How to implement the wanted behaviour? 如何实现通缉行为?

The only way I have found to do this is by setting the content hugging and compression resistance priorities of the child views to be required, something like this: 我发现这样做的唯一方法是设置子视图的内容拥抱和压缩阻力优先级,如下所示:

    let arrangedViews = [filterLabel, image]
        .map { (view: UIView) -> UIView in
            view.setContentHuggingPriority(.required, for: .horizontal)
            view.setContentCompressionResistancePriority(.required, for: .horizontal)
            return view }

    let stack = UIStackView(arrangedSubviews: arrangedViews)
    stack.axis = .horizontal
    stack.distribution = .fill
    stack.spacing = 8

With those set on the arranged subviews, do you do indeed (or at least I did) get the desired result. 如果设置在已安排的子视图中,您是否确实(或至少我做过)获得了所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM