我想在我添加到UITextView
的某些图像上添加额外的信息。该类是NSTextAttachment()
。我需要在图像中添加一些String
描述,以便应用程序知道图像中的内容。如何添加此额外功能?是通过Extension
吗?
let attachment = NSTextAttachment()
attachment.image = image
attachment.bounds = CGRect(origin: .zero, size: image.size)
// Extra properties wanted
attachment.description = "add in info about what is in attachment"
attachment.moreInfo = "some more info about the attachment"
最佳答案
class EmojiTextAttachment:NSTextAttachment{
}
private var EmotagAssociationKey:String? = nil
extension EmojiTextAttachment{
var emoticonName:String?{
get {return objc_getAssociatedObject(self,&EmotagAssociationKey) as? String ?? ""}
set {objc_setAssociatedObject(self, &EmotagAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN) }
}
}
已经有一段时间了,但是我的解决方案已经解决了。
扩展
NSTextAttachment
您可以使用
objc_getAssociatedObject
和objc_setAssociatedObject
添加参数使用时,请使用
EmojiTextAttachment
而不是NSTextAttachment
。 let emoticon:EmojiTextAttachment = EmojiTextAttachment()
let image = UIImage(named: myImage) as UIImage!
emoticon.image = image?.resizeSelf(newWidth, newHeight)
emoticon.emoticonName = emoname
objc_getAssociatedObject
https://developer.apple.com/documentation/objectivec/1418865-objc_getassociatedobject的文档