【发布时间】:2017-12-28 16:07:35
【问题描述】:
我正在尝试创建一个带有动态高度单元格的单列(一种 tableview 样式)的 collectionView。每个单元格将包含一个顶视图,其高度为 50 点,并具有单元格的前导、尾随和顶部约束。唯一的另一件事是下面的一些文本,它们将根据其内容具有动态高度。问题是我尝试使用 boundingRect 方法来计算标签的大小,但是如果文本太长,它将被切断(剪裁)并且单元格没有应有的高度。这是我的代码:
extension CustomCollectionViewController: UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let collectionViewWidth = collectionView.bounds.width
let topViewHeight: CGFloat = 50
let topAndBottomMargin: CGFloat = 8
let width = collectionViewWidth - 4 * 2
let text = answer[indexPath.item]
let s = NSString(string: "hello")
let font = UIFont.systemFont(ofSize: 15)
let height = calculateTextHeight(for: text, font: font, width: width - 100)
return CGSize(width: width, height: height + topViewHeight + topAndBottomMargin + 16)
}
func calculateTextHeight(for text: String, font:UIFont, width: CGFloat) -> CGFloat{
let attributes = [NSFontAttributeName: font]
let estimateHeight = NSString(string: text).boundingRect(with: CGSize(width: width, height: .greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil)
let string = NSString(string: text)
//let estimateHeight = string.size(attributes: [NSFontAttributeName: font])
print(estimateHeight.height)
return CGFloat(ceil(estimateHeight.height))
}
第二件事是我仍然不明白 CGSize 中的宽度如何影响整体高度?
我尝试使用 NSString.size 但这根本不起作用。它严重低估了字符串的高度
【问题讨论】:
-
单元格中的文本在UILabel中? (你设置了最大行数吗?)
-
我将它设置为 0,这样它就可以拥有尽可能多的东西
-
宽度对高度的影响非常明显,因为宽度决定了你的文字是一、二、三行还是更多。
标签: ios swift uicollectionview uicollectionviewcell