1 year ago
#345980
TSR
UICollectionViewCell Flow Layout does not place cell correctly
My goal is to show the yellow tags inline until it fills the available width, then goes to the next line.
I used UICollectionView Flow Layout to achieve that. Here is my full code stripped down to the minimum reproducible example.
What you see on Image 1 is what appears on view did load.
The problem is that the 5th yellow tag could have been placed in the same line as the others because there is enough space. What should I do with my code to achieve the image shown in image 2 ?
Weirdly, after I reload the UICollection view, the layout appears as expected on image 2. You can achieve Image 2 by clicking on the remove button once then add button once.
Along with the fix, I would appreciate a small explanation because I have spent several hours on this issue, tried so many things but nothing works.
This is the code to resize the height of the collection view.
let layoutHeight = collectionView.collectionViewLayout
.collectionViewContentSize.height
collectionViewHeight.constant = layoutHeight
This is the code to size the item cells:
func collectionView(_: UICollectionView,
layout _: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let string = tagList[indexPath.row]
let fontAttribute = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18, weight: .regular)]
let stringSize = string.size(withAttributes: fontAttribute)
let padding: CGFloat = 25
let width = stringSize.width + padding
return CGSize(width: width, height: 50)
}
Image 1 (wrong, the 5th cells should be to the right of the 4th, not below)
Image 2 (Right, expected behaviour, can be achieved but reloading the collection view)
ios
swift
xcode
uicollectionview
uicollectionviewcell
0 Answers
Your Answer