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

Sté*_*uca 14 height uitableview ios swift2 uistackview

我希望有一个类似于<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
}
Run Code Online (Sandbox Code Playgroud)

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

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

我怎么能解决这个问题?

Yuc*_*ong 6

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

在此输入图像描述 在此输入图像描述

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

为了证明这将起作用,我有这个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
}
Run Code Online (Sandbox Code Playgroud)

这是最终结果:

https://github.com/yzhong52/AutosizeStackview