如何在 UITableViewCell 中创建具有动态高度的视图网格 [英] How to create a grid of views with dynamic height in UITableViewCell
问题描述
我想创建一个盒子网格,这些盒子是 Label
在我的 UITableViewCell
中具有固定宽度和高度的.这怎么办?
I would like to create a grid of boxes, which are Label
's with fixed width and height within my UITableViewCell
's. How can this be done?
我想要这个:
我明白了:
我尝试在 UITableViewCell
中使用 UICollectionView
但我遇到了两个问题:
I tried using a UICollectionView
within the UITableViewCell
but I am running in to two problems:
UITableViewCell
的高度不会根据项目的数量动态变化- 无法精确设置项目之间的空间(因为您只能定义一个 minCellSpacing 值)
- the
UITableViewCell
's height is not dynamically changing according to how many items there are - the space between items can't be set exactly (since you can only define a minCellSpacing value)
我的问题:
创建这个 Label
网格的最佳方法是什么,以便 UITableViewCell
的高度将根据项目数量动态变化,所以我可以准确设置项目之间的间距?
What is the best way to create this grid of Label
's such that the UITableViewCell
's height will change dynamically based on number of items, and so I can set the spacing between items exactly?
(如果不用 UICollectionView
也能完成,那会很好,但这不是必需的)
(If it can be done without UICollectionView
that would be nice, but it's not a requirement)
推荐答案
这是 initWithStyle:reuseIdentifier:
方法的更新版本,可确保标签为 30x30:
Here's an updated version of the initWithStyle:reuseIdentifier:
method that ensures that the labels are 30x30:
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let count = 16 + Int(arc4random_uniform(16))
print(count)
let rows = Int(ceil(Double(count) / Double(ColumnCount)))
let columnView = LMColumnView()
for var i = 0; i < rows; i++ {
let rowView = LMRowView()
rowView.height = 30
columnView.addArrangedSubview(rowView)
for var j = 0; j < ColumnCount; j++ {
let number = Int(arc4random_uniform(150))
let label = UILabel()
if (i * ColumnCount + j < count) {
label.text = String(number)
label.width = 30
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.greenColor()
}
rowView.addArrangedSubview(label)
}
rowView.addArrangedSubview(LMSpacer())
}
appendMarkupElementView(columnView)
}
它使用 8 像素的默认间距,但您可以通过 LMColumnView
和 LMRowView
的 spacing
属性更改它.
It uses the default spacing of 8 pixels, but you can change that via the spacing
property of LMColumnView
and LMRowView
.
这篇关于如何在 UITableViewCell 中创建具有动态高度的视图网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!