簡體   English   中英

如何在 CollectionView 中將單元格高度調整為 Label 高度?

[英]How to resize cell height to Label height in CollectionView?

我用 Xcode 使用 Swift 和 collectionView 和 collectionViewCell 制作了一個應用程序。 我從我的 WordPress 網站上獲取了帖子,其中一類只是文本,我想在 ViewController 上顯示全文。 現在的問題是我正在使用它作為單元格高度..

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    
    var returnValue = CGSize()
    
    if (indexPath.item % 5 == 4){
        
        if UIScreen.main.bounds.size.height > 960{ //Write iPhone or iPad size. If iPad :
            returnValue = CGSize(width: (((view.frame.width) - 40) / 2), height: 100)
        } else { //if iPhone
            returnValue = CGSize(width: view.frame.width-20 , height: 100)
        }
        
    } else {
        
        if UIScreen.main.bounds.size.height > 960{ //Write iPhone or iPad size. If iPad :
            returnValue = CGSize(width: (((view.frame.width) - 40) / 2), height: 180)
        } else { //if iPhone
            returnValue = CGSize(width: view.frame.width-20 , height: 180)
        }
        
    }
               
    return returnValue
}

現在,當 ViewController 上的帖子顯示比文本只顯示單元格的高度而其他文本只是隱藏時,我如何根據 Label 高度調整單元格的大小?

很簡單,只需計算 label 的高度(不要忘記頂部和底部的間距)。

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 ceil(boundingBox.height)
}

暫無
暫無

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

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