[英]Auto collection view cell Height
I have a custom cell with a label.我有一个带有 label 的自定义单元。 I get the text from the server, and the cell in the collection must choose the height so that all the text fits and is visible.
我从服务器获取文本,集合中的单元格必须选择高度,以便所有文本都适合并且可见。 Now I use this method, but I do not know how to change the height so that it adjusts.
现在我使用这种方法,但我不知道如何更改高度以使其调整。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.bounds.width, height: 90)
}
Step 1:- Create a function to estimate the size of your text: This method will return a height value that will fit your string!第 1 步:- 创建一个 function 来估计文本的大小:此方法将返回适合您的字符串的高度值!
private func estimateFrameForText(text: String) -> CGRect {
//we make the height arbitrarily large so we don't undershoot height in calculation
let height: CGFloat = 999
let size = CGSize(width: yourDesiredWidth, height: height)
let options = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin)
let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(18, weight: UIFontWeightLight)]
return NSString(string: text).boundingRectWithSize(size, options: options, attributes: attributes, context: nil)
}
Step 2: Use or override delegate method below:第 2 步:使用或覆盖下面的委托方法:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var height: CGFloat = 0
//we are just measuring height so we add padding constant to give the label some room to breathe!
var padding: CGFloat = 10
let stringFromViewModel = “Hello please pass your string here from array…”
//estimate each cell's height
height = estimateFrameForText(stringFromViewModel).height + padding
return CGSize(width: yourDesiredWidth, height: height)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.