Reputation: 85
I have tried to create self-sizing collectionView cell
, but my label doesn't want to expand his height and become multilines, instead the label just goes in one single line and my cell goes beyond of collectionView frame. I have created my own custom UICollectionViewFlowLayout and tried to handle all stuff there. What have I done wrong? Looking forward for your answers, thanks!
My implementation:
class VerticalLayout:UICollectionViewFlowLayout {
override func prepare() {
super.prepare()
self.scrollDirection = .vertical
self.minimumLineSpacing = 0
self.minimumInteritemSpacing = 0
self.estimatedItemSize = CGSize(width: UIScreen.main.bounds.width, height: 173)
self.sectionInset = .zero
}
}
Upvotes: 0
Views: 79
Reputation: 390
You must count text height and pass it to your collectionview delegate method
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let itemHeight: CGFloat = estimatedHeightForText(text: items[indexPath.item].text, fontSize: fontSize, fontWeight: fontWeight, width: widthForText) + someRawValue // here count height for cell
var itemWidth: CGFloat = someRawVal
return CGSize(width: itemWidth, height: itemHeight)
}
Count it here
func estimatedHeightForText(text: String, fontSize: CGFloat, fontWeight: UIFont.Weight, width: CGFloat) -> CGRect {
let size = CGSize(width: width, height: 1000)
let font = UIFont.systemFont(ofSize: fontSize, weight: fontWeight)
return NSString(string: text).boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: font], context: nil)
}
UPD. widthForText - this is important value for text width in your cell. Count it properly
Upvotes: 2