gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:48:49 26 4
gpt4 key购买 nike

我想计算文本的高度以获得 Collection View 单元格的估计高度。我在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com