I am trying to understand why Collection View keeps centre aligning just the last cell in a collection.
I have created a simple Flow layout based collection view. I am using the Autolayout flag - which I am not sure is causing this issue.
Whenever I remove a cell from the Collection view - the first few seem to work fine and roll to the left. However when I remove the second last one, then suddenly the last cell changes from being left aligned to being centre aligned. Does anyone have an explanation? It seems strange.
How do I make it so that all the cells will roll to the left and stay aligned to the left.
Edit: here is the view hierachy debugging: https://i.stack.imgur.com/mCGzH.jpg
Here is the view Behaviour
I have made a simple github to demo it: https://github.com/grantkemp/CollectionViewIssue
and here is the code:
var dataforCV = ["short","longer phrase", "Super long Phrase"]
override func viewDidLoad() {
super.viewDidLoad()
demoCollectionView.reloadData()
let layout = UICollectionViewFlowLayout()
// Bug Description - > UICollectionViewFlowLayoutAutomaticSize will center Align the layout if it has only a single cell - but it will left align the content if there is more than one cell.
// I would expect this behaviour to be consistently left aligning the content.
//How to repeat: If you comment out UICollectionViewFlowLayoutAutomaticSize then the collection view will show 3 cells being left aligned and it will continue to left align all the content no matter how many cells you remove.
// But: if you leave turn UICollectionViewFlowLayoutAutomaticSize on - then it will intially show 3 cells being left aligned, and then as you click to remove each cell they will stay left aligned until the last single cell will suddenly center align in the collection view
// see here for the screen recording:https://i.stack.imgur.com/bledY.gif
// see here for the view hierachy debuggins screen: https://i.stack.imgur.com/mCGzH.jpg
layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
// <-- End Bug Description
demoCollectionView.collectionViewLayout = layout
}
//MARk: CollectionView
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? collectionCell
cell?.text.text = dataforCV[indexPath.row]
return cell!
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataforCV.count
}
//Remove the item from the array if selected
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
dataforCV.remove(at: indexPath.row)
demoCollectionView.deleteItems(at: [indexPath])
}