计算要在collectionView单元格中使用的NSString高度

时间:2017-07-22 17:34:35

标签: ios swift uicollectionview uicollectionviewcell

我正在尝试使用单个列(一种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,但根本不起作用。它严重低估了字符串的高度

0 个答案:

没有答案
相关问题