自动集合视图单元格高度
Auto collection view cell Height
我有一个带标签的自定义单元格。我从服务器获取文本,集合中的单元格必须选择高度,以便所有文本适合且可见。现在我用这个方法,但我不知道如何改变高度来调整。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.bounds.width, height: 90)
}
第 1 步:- 创建一个函数来估计文本的大小:此方法将 return 一个适合您的字符串的高度值!
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)
}
第 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)
}
我有一个带标签的自定义单元格。我从服务器获取文本,集合中的单元格必须选择高度,以便所有文本适合且可见。现在我用这个方法,但我不知道如何改变高度来调整。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.bounds.width, height: 90)
}
第 1 步:- 创建一个函数来估计文本的大小:此方法将 return 一个适合您的字符串的高度值!
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)
}
第 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)
}