UIStackView调整高度到子视图

时间:2016-11-19 20:09:07

标签: ios swift uitableview uikit uistackview

我想让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

(在此代码中高度和宽度为0)

如何实现想要的行为?

1 个答案:

答案 0 :(得分:3)

我发现这样做的唯一方法是设置子视图的内容拥抱和压缩阻力优先级,如下所示:

    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

如果在已安排的子视图中设置了这些,您是否确实(或至少我做过)获得了所需的结果。