如何为自定义字体声明NSAttributedStringKey.font?

时间:2017-11-06 20:42:56

标签: swift

我想计算文本的高度以获得集合视图单元格的估计高度。我在collectionViewLayout函数;

中使用以下代码
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    if let messageText = messages[indexPath.row]?.text {

        let size = CGSize(width: view.frame.width, height: 1000)
        let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
        let estimatedFrame = NSString(string: messageText).boundingRect(with: size, options: options, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17)], context: nil)
        return CGSize(width: view.frame.width, height: estimatedFrame.height + 20)
    }

    return CGSize(width: view.frame.width, height: 100)
}

这适用于系统字体,但不适用于我项目中的自定义字体。问题是estimatedFrame不等于系统字体的结果。我认为问题将是选项的主题:attributes。对于自定义字体有没有类似UIFont.systemFont(ofSize: 17)的方式?

1 个答案:

答案 0 :(得分:3)

如果我正确地读你的问题,你想要:

UIFont(name: "yourCustomFontNameString", size: 17)

所以:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    if let messageText = messages[indexPath.row]?.text {

        let size = CGSize(width: view.frame.width, height: 1000)
        let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
        let estimatedFrame = NSString(string: messageText).boundingRect(with: size, options: options, attributes: [NSAttributedStringKey.font: UIFont(name: "yourCustomFontNameString", size: 17)], context: nil)
        return CGSize(width: view.frame.width, height: estimatedFrame.height + 20)
    }

    return CGSize(width: view.frame.width, height: 100)
}