3

CollectionView具有标题和自定义布局。 当我点击单元格时,有两种方法正在工作。 1)didSelectItemAt 2)viewforsupplementaryelementofkind 我点击单元格并scrollToItem到页面的开头。 无法动态检测标题中的detailPhotoStory大小。滚动时,Uicollectionview没有更新标题

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) 
    } 
+0

请更具体到你想问什么。你正在谈论哪种标签尺寸? – Ishika

+0

使用这个referenceSizeForHeaderInSection,从你的内容中获取高度并返回你的高度 – karthikeyan

+0

@karthikeyan我使用了referenceSizeForHeaderInSection,但是collectionview的头部没有改变。 – Oztemir

回答

0

您可以像这样创建的字符串的扩展,并用它按宽度来获得标签的高度和使用的字体。您可以使用使用返回的高度来指定单元格的高度。

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 
    } 
} 

来源是this ans。