我想计算文本的高度以获得集合视图单元格的估计高度。我在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)
这样的自定义字体的方法? 最佳答案
如果我没看错你的问题,你想:
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)
}
关于swift - 如何声明NSAttributedStringKey.font为自定义字体?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47145432/