Reputation: 9419
I have a collection view that contains a cell with varying width (it has a label inside it):
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)
}
}
How do I make the collection view's height dynamic? The problem is that at init time I don't know what frame I should give to the collection view, so I just give zero:
let layout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
How do I make the collection view height dynamic?
I have also looked into the sizeForItem
method:
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
}
but I think this returns a size of zero width and heigth.
Upvotes: 0
Views: 81
Reputation: 100533
First here set an assumption height , but the width should be known
let collectionView = UICollectionView(frame:CGRect(x:0,y:20,width:self.view.frame.width,height:300), collectionViewLayout: layout)
Then in 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)
For a total height , create a function from above and call it with all your items then add the heights and set them to collectionView's height
Upvotes: 1