簡體   English   中英

UICollectionView動態頭大小計算

[英]UICollectionView dynamic header size calculation

我知道圍繞這個主題已經有很多帖子,但他們不知何故沒有引導我找到解決方案,此時,經過幾天的努力,我不知道該怎么做。

所以我有一個UICollectionView ,我有一個標題。 對於標題,我創建了自己的UICollectionReusableView 它包含一個StackView,里面有兩個標簽。 它們都有動態大小(Lines = 0)。 這些是StackView的約束(我也嘗試將底部約束設置為= 0):

StackView約束

屏幕截圖

我像這樣計算標題大小......

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    let item = displayItems.object(at: UInt(section)) as! MySectionDisplayItem

    let reusableView: MyReusableView = UIView.fromNib()
    reusableView.setTitle(text: item.getTitle())
        .setSubtitle(subtitle: item.getSubtitle())

    return reusableView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
}

...並返回要顯示的視圖,如下所示:

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    let item = displayItems.object(at: UInt(indexPath.section)) as! MySectionDisplayItem

    let reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "myReusableView", for: indexPath) as! MyReusableView

    reusableView.setTitle(text: item.getTitle())
        .setSubtitle(subtitle: item.getSubtitle())

    return reusableView
}

在我的UICollectionReusableViewUICollectionView中,啟用了自動布局。

我試過的一些事情:

  • preferredMaxLayoutWidth設置為標簽上的不同正值
  • 將標簽嵌入單獨的視圖中
  • 使用約束而不是使用StackView

我希望我沒有混淆我發現的一些解決方案,但無論如何我不認為這樣一個“簡單”的東西可能很難實現。

我終於通過約束寬度解決了這個問題:

reusableView.translatesAutoresizingMaskIntoConstraints = true
reusableView.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width).isActive = true

可能你還必須使用內容抗壓性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM