如何根据其内容调整UIStackView的大小?

问题描述 投票:13回答:1

我希望有一个类似于<Table> HTML标签的行为,在这种意义上,框架的大小根据其内容而定。

在我的上下文中,我使用UIStackView作为UITableViewCell的内容视图。由于单元格中的项目是各种信息,因此单元格的最终高度应该是可变的。

我的策略是以编程方式将单元格构建为具有.Vertical轴的UIStackView,如下面的代码片段所示:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    let sv = UIStackView(frame: tableview.frame)
    sv.axis = .Vertical
    cell.addSubview(sv)
    for i in information {
        let l = UILabel()
        l.text = i
        sv.addSubViewAndArrange(l)
    }

    return cell
}

不幸的是,单元格大小不适应内容,因此我必须自己设置单元格高度,如下所示:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return cellHeight     // a constant
}

我怎么能解决这个问题?

ios uitableview swift2 height uistackview
1个回答
6
投票

UIStackView旨在根据内容增加其大小。为了使其起作用,您需要在UIStackViewUITableViewCell之间设置约束。例如,这是约束在界面构建器中的样子:

enter image description here enter image description here

如果你喜欢在代码中设置约束,那也应该有效。

为了证明这将起作用,我有cellForRowAt函数。基本上,它在UILabel中放置了一些UIStackView,标签数量取决于行号。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TableviewCell", for: indexPath) as! TableviewCell
    for i in 1...indexPath.row + 1 {
        let label = UILabel()
        label.text = "Row \(indexPath.row), Label \(i)"
        cell.stackView.addArrangedSubview(label)
    }
    return cell
}

这是最终结果:

https://github.com/yzhong52/AutosizeStackview

© www.soinside.com 2019 - 2024. All rights reserved.