Uicollectionview does not update title on scroll
CollectionView has a header and custom layout. When I click on a cell 2 methods work. 1) didSelectItemAt 2) viewforsupplementaryelementofkind I click on a cell and scrollToItem to the top of the page. Unable to size detailPhotoStory in header dynamically.
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)
}
+3
source to share
1 answer
You can create a line extension this way and use it to get the height of the caption to match the width and font. You can use the use height to assign the cell height.
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 this ans.
0
source to share