I am working on remastering Swift and UIKit after a long time.
WorkFlow:
- I have created a ViewController with a
UICollectionView
aligning its centers in both X and Y axis and Proportional Width and Height to Root View. - Assigned to collectionview.delegate and collectionView.dataSource it appropriate class instance corresponding to
UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
- I have created a UICollectionViewCell and called dequeuereusablecell... in cellforItemAt...
- I have access to sizeForItemAt... to calculate appropriate size
// item count represents number of cells per row in a section within collectionview let refWidth = collectionView.frame.width / CGFloat(itemCount); // sectionInsets are UIEdgeInsets.zero for simplicity in reproducing the issue let calculatedSize = CGSize(width: refWidth, height: refWidth/2 )
- Implemented
traitCollectionDidChange
in ViewController and forced reloadData on collectionView - I have been testing with many Devices (Simulators to be exact) it works for most cases
Scenario:
- If both the horizontal and vertical Size classes are exactly same - Example:
iPad Mini
- ItemCount is 1
- Page is first opened in Landscape
- Then the Page is rotated into Portrait
Issue:
- Collection Does not Reload as the traitcollection has not changed.
- Current width of the Cell is greater than the current width of CollectionView
Few of Approaches I tried:
- In cellForItemAt... method, before returning the cell, I have added a constraint to cell with CollectionView as follows - `Applicatin Crashed with a message that such a constraint cannot be applied.
let itemCount = itemsPerRowInEachSection(collectionView) if cell.contentView.constraints.first(where: { cst in cst.identifier == "widthConst" }) != nil { let newConst = NSLayoutConstraint(item: cell, attribute: .width, relatedBy: .equal, toItem: collectionView, attribute: .width, multiplier: CGFloat(1)/CGFloat(itemCount), constant: 0) newConst.identifier = "widthConst" cell.addConstraint(newConst) }
- Similar to first approach but tried applying constraint in interfacebuilder. There was no way to do that as command click and drag between the CollectionView and CollectionViewCell does not prompt any constraints at all
Question:
- Should I implement somehthing like a orientation change listener and reload the collectionView there instead of trait collection change listener?
- If I go for orientation Listener, In future if I work on, multi tasking support, If I change traitCollection withut changing the Orientation, this approachdoes not work.
- If I implement both traitCollection and Orientation Change Listeners, lot of times they collide and will attempt to reload collectionView twice.
- Can someone hep me with finding appropriate solution for this issue?