ios - 根据内容使集合视图高度动态
问题描述
我有一个包含不同宽度的单元格的集合视图(它里面有一个标签):
public class TagView: UIView {
let textLabel: UILabel = {
let label = UILabel()
label.textColor = .black
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 15)
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
setupLabel()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
backgroundColor = #colorLiteral(red: 0.03529411765, green: 0.6862745098, blue: 0.003921568627, alpha: 1)
backgroundColor = backgroundColor
layer.cornerRadius = 3
layer.masksToBounds = true
}
private func setupLabel() {
addSubview(textLabel)
textLabel.fillToSuperview(constant: 3)
}
}
如何使集合视图的高度动态化?问题是在初始化时我不知道应该给集合视图什么框架,所以我只给零:
let layout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
如何使集合视图高度动态化?
我也研究了sizeForItem
方法:
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let view = TagView()
let data = tags[indexPath.row]
view.textLabel.text = data
view.layoutSubviews()
return view.frame.size
}
但我认为这会返回零宽度和高度的大小。
解决方案
首先在这里设置一个假设高度,但宽度应该是已知的
let collectionView = UICollectionView(frame:CGRect(x:0,y:20,width:self.view.frame.width,height:300), collectionViewLayout: layout)
然后在sizeForItemAt
let fixedWidth = (collectionView.frame.width - 40 ) / 5 // say here you need 5 items / row
let label = UILabel()
label.numberOfLines = 0
label.font = UIFont.systemFont(ofSize: 15)
let si = label.sizeThatFits(CGSize(width:fixedWidth, height: CGFloat.greatestFiniteMagnitude))
// si.height is the needed height with 6 padding from top and bottom according to your constant in tagView
return CGSize(width:fixedWidth + 6.0 ,height:si.height)
对于总高度,从上面创建一个函数并使用所有项目调用它,然后添加高度并将它们设置为 collectionView 的高度
推荐阅读
- openlayers - OpenLayers:实用程序 getSource().on 等待一秒钟以加载或重新加载 TileLayer
- css - 仅在 Windows 上应用滚动条样式
- c# - 如何在运行时 C# 获取 azure 函数 URL
- math - 根据数量增加掉落机会
- android - 在 Flutter 中使用 Shared Preferences 来处理不同路线之间的数据?
- hyperlink - 如何在 Tableau 工具提示中的图像上创建超链接?
- batch-file - 鼠标迷宫批处理文件
- node.js - 相同nodejs方法的解决方法
- reactjs - 如何将现有路径名和不存在的路径名重定向到路径名?
- python - Openvino 将二进制文件加载到 blob 中