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

我希望有一个类似于

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 } 

我怎么能解决这个问题?

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

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

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

为了certificate这将起作用,我将其用于cellForRowAt函数。 基本上,它在UIStackView放置了许多UILabel ,标签数量取决于行号。

 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