如何根据其内容调整UIStackView的大小? [英] How to size a UIStackView depending on its content?

查看:1271
本文介绍了如何根据其内容调整UIStackView的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to have a similar behavior than the <Table> HTML tag, in the sense where the frame is sized according to its content.

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

In my very context, I use an UIStackView as the content view of a UITableViewCell. As items in the cell are various information, the resulting height of the cell should be variable.

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

My strategy is to programmatically build a cell as a UIStackView with a .Vertical axis, as in the code snippet as follows:

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
}

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

Unfortunately, the cell size does not adjust to the content, and as a result I have to set the cell height myself, as follows:

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

我如何修复那个?

推荐答案

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

UIStackView is designed to grow its size according to the content. In order for that to work, you need to set up the constraints between the UIStackView and the UITableViewCell. For example, this is how the constraints look like in interface builder:


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

If you like setting up constraints in code, that should work too.

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

To demonstrate that this will work, I have this for the cellForRowAt function. Basically, it puts a number of UILabel inside the UIStackView and the label count is depending on the row number.

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

这篇关于如何根据其内容调整UIStackView的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆