[英]NSString.boundingRect fails with "[NSNull renderingMode]: unrecognized selector sent to instance" when specifying font
我正在尝试制作一个集合视图,其中单元格仅包含 label,并且我希望每个单元格的宽度与文本的宽度相匹配。 为了找到具有特定字体的每个字符串的宽度(以便我可以使用CollectionView.sizeForItemAt
返回该大小),我调用了NSString.boundingRect
。 但是,每当我在attributes
参数中指定字体时,我的项目都会因'NSInvalidArgumentException', reason: '-[NSNull renderingMode]: unrecognized selector sent to instance
错误。
这是我如何调用boundingRect
:
let size = CGSize(width: 200, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let attributes = [NSAttributedString.Key.font: UIFont(name: "SF Pro Text", size: 14)]
let size = NSString(string: "test").boundingRect(with: size, options: options, attributes: attributes, context: nil)
您可能没有指定字体,所以我将更改代码以确保:
let size = CGSize(width: 200, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let font = UIFont(name: "SF Pro Text", size: 14) ?? UIFont.systemFont(ofSize: 14)
let attributes = [NSAttributedString.Key.font: font]
let size1 = NSString(string: "test").boundingRect(with: size, options: options, attributes: attributes, context: nil)
如果要查看所有可能字体的列表,请使用:
let familyNames = UIFont.familyNames
for name in familyNames {
UIFont.fontNames(forFamilyName: name).forEach { print($0) }
}
当在您的项目中找不到指定的字体时,会发生此错误。 检查您的字体文件最近是否有更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.