Skip to content

Instantly share code, notes, and snippets.

@roma86
Last active May 9, 2019 22:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roma86/319ef5321253817e021a7ce25895207a to your computer and use it in GitHub Desktop.
Save roma86/319ef5321253817e021a7ce25895207a to your computer and use it in GitHub Desktop.
This is only works for one section and on header
/// Header setup for content size calucation
class ProductHeader: UICollectionReusableView {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var detailsLabel: UILabel!
class func createFromNib(product: Product) -> ProductHeader {
let view = NSBundle.mainBundle().loadNibNamed("ProductHeader", owner: nil, options: [:]).last! as! ProductHeader
view.setup(product)
return view
}
func computeHeightWithContent(forWidth width: CGFloat) -> CGFloat {
frame.size.width = width
setNeedsLayout()
layoutIfNeeded()
return systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
}
func setup(product: Product) {
detailsLabel.text = product.details
}
}
/// Collection view subclass
class ProductDetailsCtrl: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate {
var product: Product!
/// Cache calcualated height
var headerHeight: CGFloat = 200.0
override func viewDidLoad() {
super.viewDidLoad()
// Calculate and cache header height after all content setups.
let headerView = ProductHeader.createFromNib(product)
headerHeight = headerView.computeHeightWithContent(forWidth: view.bounds.width)
// Register header nib
let headerNib = UINib(nibName: "ProductHeader", bundle: nil)
collectionView.registerNib(headerNib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: ReusableView.ProductHeaderView)
}
}
/// Adjust header height
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section == 0 {
return CGSize(width: 0, height: headerHeight)
} else {
return CGSizeZero
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment