3

CollectionView has header and custom layout. When I click on the cell, 2 methods are working. 1) didSelectItemAt 2) viewforsupplementaryelementofkind I click on the cell and scrollToItem to the beginning of the page. Can not detect the detailPhotoStory size in header dynamically.

enter image description here

var headerHeight: CGFloat = 0.0
var headerView: DetailCollectionReusableView?

//viewForSupplementaryElementOfKind

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String,at indexPath: IndexPath) ->UICollectionReusableView {
        if kind == UICollectionElementKindSectionHeader
        {

            headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader,
                                                                         withReuseIdentifier: "detailCollectionReusableView",
                                                                         for: indexPath) as? DetailCollectionReusableView

            headerView?.detailPhotoStory.text = PhotoItemArraySelected[indexPath.row].photoStory

            headerView?.setNeedsLayout()
            headerView?.layoutIfNeeded()
            headerHeight = 380
            headerHeight += (headerView?.detailPhotoStory.frame.height)!

            return headerView!
        }

        return UICollectionReusableView()
    }

//didSelectItemAt

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        headerView?.detailPhotoStory.text = PhotoItemArraySelected[0].photoStory
        headerView?.setNeedsLayout()
        headerView?.layoutIfNeeded()

        headerHeight = 380
        headerHeight += (headerView?.detailPhotoStory.frame.height)!

        collectionView.reloadData()
        collectionView.scrollToItem(at: IndexPath(row: 0, section: 0),
                                    at: .top,
                                    animated: true)
    }
Oztemir
  • 43
  • 5

1 Answers1

0

You can create String extension like this and use it to get label height according to width and used font. You can use use returned height to assign height of cell.

extension String {
     func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
         let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
         let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

         return boundingBox.height
  }
}

Source being this ans.

luckyShubhra
  • 2,731
  • 1
  • 12
  • 19