Here is how you can handle custom UICollectionViewReusableView with auto layout without the XIB file.
- Implement the
referenceSizeForHeaderInSection
delegate method.
- In it, instantiate the view that you use as a header view.
- Set its visibility to hidden, to avoid flashing.
- Add the view to the collectionview's superview.
- Set it's layout using auto layout, to match the expected visual outcome of the header.
- Invoke
setNeedsLayout
and layoutIfNeeded
- Remove the view from the superview
CAUTION: I am not a big fan of this solution, as it adds the custom view to the collectionview's superview each time, to perform calculations. I didn't notice any performance issues though.
CAUTION #2: I'd treat it as a temporary solution, and migrate to self sizing supplementary views once they get published.
I am using PureLayout for autolayout purposes.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
let header = CustomHeaderView()
header.isHidden = true;
self.view.addSubview(header)
header.autoPinEdge(toSuperviewEdge: .leading)
header.autoPinEdge(toSuperviewEdge: .trailing)
header.autoPin(toTopLayoutGuideOf: self, withInset: 0)
header.setupHeader(withData: self.data)
header.setNeedsLayout()
header.layoutIfNeeded()
header.removeFromSuperview()
return header.frame.size
}