问题描述
我目前有一个 UITextView,它显示一个 NSAttributedString,其中包含带有文本和图像的 HTML 数据。此数据通过 API 接收,因此图像和文本都合并为一个 HTML 字符串。这是解析 HTML 的函数。
let htmlData = NSString(string: myString).data(using: String.Encoding.unicode.rawValue);
let options = [NSAttributedString.DocumentReadingOptionKey.documentType:
NSAttributedString.DocumentType.html];
do{
let text = try NSMutableAttributedString(data: htmlData ?? Data(),options: options,documentAttributes: nil);
text.addAttribute(NSAttributedString.Key.font,value: UIFont(name: "Arial",size: CGFloat(fontSize)) as Any,range: NSMakeRange(0,text.length));
return text;
}
catch let error{
print(error);
return NSMutableAttributedString(string: myString);
}
当长按图像时,会出现一个菜单,其中包含两个选项(1. 复制图像 2. 保存到相机胶卷)。当我单击“复制图像”时,应用程序崩溃并显示以下错误消息:
Terminating app due to uncaught exception 'NSInvalidArgumentException',reason: '-[_UIConcretePasteboard setImage:]: Argument is not an object of type UIImage [(null)]'
有谁知道如何解决这个问题,所以当长按图像并选择复制图像时,它不会崩溃?
解决方法
您需要将图像从 html 转换为 NSTextAttachment,就像将文本转换为 NSAttributedString 一样。当将这些附件附加到 NSAttributedString 时。
它可能看起来像这样:
let htmlData = NSString(string: myString).data(using: String.Encoding.unicode.rawValue)
let options = [NSAttributedString.DocumentReadingOptionKey.documentType:
NSAttributedString.DocumentType.html]
let image = UIImage(named: IMAGENAME_FROM_HTML) ?? UIImage()
let imageAttachment = NSTextAttachment(image: image)
do {
let text = try NSMutableAttributedString(data: htmlData ?? Data(),options: options,documentAttributes: nil)
text.addAttribute(.font,value: UIFont(name: "Arial",size: CGFloat(fontSize),range: NSMakeRange(0,text.length))
let textWithAttachment = try NSAttributedString(attachment: imageAttachment)
text.replaceCharacters(in: NSMakeRange(RANGE_FOR_IMAGE_IN_HTML),with: textWithAttachment)
return text
}
catch let error {
print(error)
return NSMutableAttributedString(string: myString)
}
附言不要在 swift 结尾的行上使用分号。