![](/img/trans.png)
[英]How to resize CollectionView cell height according to image in cell in swift?
[英]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.