Skip to content

Instantly share code, notes, and snippets.

@badrinathvm
Created July 26, 2019 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save badrinathvm/b025a426b77609df85556d7d1de5291a to your computer and use it in GitHub Desktop.
Save badrinathvm/b025a426b77609df85556d7d1de5291a to your computer and use it in GitHub Desktop.
dynamic height of the collectionView
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = calculateDynamicHeightOftheCell(index: indexPath.row)
return CGSize(width: self.collectionView.bounds.width, height: height)
}
/**
Calculates the height of the card based on the content inside the view.
- parameters:
- index = identifies which cell it is.
*/
func calculateDynamicHeightOftheCell(index: Int) -> CGFloat {
let creditCard = data[index]
let arbitraryHeight: CGFloat = 1000
//basically subtract leading and trailing spaces set for the view when laying out. for eg: we have two 16 collectionview leading and trailing spaces, two 24 view leading and trailing spaces.
let approximateWidthOfComponent = view.frame.size.width - 16 - 16 - 24 - 24
//calculate the approximate height of the credit card name label , with arbitrary height of 1000
let sizeOfLabel1 = CGSize(width: approximateWidthOfComponent, height: arbitraryHeight)
//Get the attributes of the label
let attributesForLabel1 = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.bold)]
//calculate the new frame the above calculated attributes and approximate height
let estimatedFrameForLabel1 = NSString(string: creditCard.name).boundingRect(with: sizeOfLabel1, options: .usesLineFragmentOrigin, attributes: attributesForLabel1, context: nil)
//Calculate the actual height by adding the above newly generated frames plus the static heights of the other components and stand spacings between them for eg: credit card image is static height (137) , read more button height (20) , standard spacings ( 4 * 16 ) , APR view height (248) etc..
let height = estimatedFrameForLabel1.height + estimatedFrame.height + 287 + 248
return height
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment