I am working on remastering Swift and UIKit after a long time.
WorkFlow:
UICollectionView
aligning its centers in both X and Y axis and Proportional Width and Height to Root View.UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
// 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 )
traitCollectionDidChange
in ViewController and forced reloadData on collectionViewScenario:
iPad Mini
Issue:
Few of Approaches I tried:
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)
}
Question:
As per OP comment...
If you need to modify layout based on the size of the view - such as on device rotation - you can use:
func viewWillTransition(to size: CGSize,
with coordinator: UIViewControllerTransitionCoordinator)
From Apple's docs:
UIKit calls this method before changing the size of a presented view controller’s view. You can override this method in your own objects and use it to perform additional tasks related to the size change. For example, a container view controller might use this method to override the traits of its embedded child view controllers. Use the provided coordinator object to animate any changes you make.