[英][__NSCFType set]: unrecognized selector with NSAttributedString:draw() gets called, based on width of position
如果运行下面的代码,它会导致异常
'NSInvalidArgumentException',原因:'-[__NSCFType set]:无法识别的选择器发送到实例 0x283130be0'
但是,可以通过将positionRect
中的宽度值从 100.0 减小来移除异常,例如将其设置为 50.0 之类的值可以移除异常。
但这是为什么呢? 为positionRect
指定的宽度值为 100.0,这远远imageSize
的宽度。 即使存在一些大小问题,为什么会出现无法识别的选择器异常?
let imageSize = CGSize(width: 400, height: 100)
let testRenderer = UIGraphicsImageRenderer(size: imageSize)
let testImage = testRenderer.image { context in
context.cgContext.setFillColor(UIColor.black.cgColor)
context.fill(CGRect(origin: .zero, size: imageSize))
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .left
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 8.0),
.paragraphStyle: paragraphStyle,
.foregroundColor: UIColor.white.cgColor
]
let attributedString = NSAttributedString(string: "This is some text", attributes: attributes)
let positionRect = CGRect(x: 10, y: 10, width: 100.0, height: 8.0)
attributedString.draw(with: positionRect, options: .usesLineFragmentOrigin, context: nil)
}
问题是由于为attributes
字典中的.foregroundColor
键传递了CGColor
而不是UIColor
。 文件指出:
在 macOS 中,这个属性的值是一个 NSColor 实例。 在 iOS、tvOS、watchOS 和 Mac Catalyst 中,该属性的值是一个 UIColor 实例。 使用此属性指定呈现期间文本的颜色。 如果您不指定此属性,则文本呈现为黑色。
NSAttributedString
代码正尝试调用set
错误指示的提供的颜色。 这在显示 Objective-C 语法-[__NSCFType set]
的错误消息中指出。 这表明set
正在 __NSCFType 类型的__NSCFType
上被调用,它是代表许多 Core Foundation(和 Core Graphics)类型的内部类型,例如CGColor
。
简而言之,更改行:
.foregroundColor: UIColor.white.cgColor
到:
.foregroundColor: UIColor.white
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.