在func setup()中,您需要生成attributeString并在附件中保存图像。
let attachment = NSTextAttachment()
attachment.bounds = CGRect(x: 0, y: 0, width: newImageWidth, height: newImageHeight)
attachment.image = attachImage // saving from cache or storage memory
var attributedString = NSMutableAttributedString(attributedString: "your note text")
attributedString.append(NSAttributedString(attachment: attachment))
self.tvContent.attributedText = attributedString
但是:如果您将整个 attributedString 存储在 note.content 中。然后传递它 self.tvContent.attributedString
private func setup() {
tfTitle.layer.borderWidth = 1
tfTitle.layer.borderColor = UIColor.darkGray.cgColor
tfTitle.text = note.title
tvContent.layer.borderWidth = 1
tvContent.layer.borderColor = UIColor.darkGray.cgColor
tvContent.text = note.content
// var attributedString: NSMutableAttributedString!
// attributedString = NSMutableAttributedString(attributedString: self.tvContent.attributedText)
// tvContent.attributedText = attributedString
// tvContent.attributedText = NSAttributedString(string: note.content)
// tvContent.textStorage.insert(NSAttributedString(string: note.content), at: 0)
}
//Insert the image
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true, completion: nil)
results.forEach { result in
result.itemProvider.loadObject(ofClass: UIImage.self) { object, error in
if let image = object as? UIImage, error == nil {
self.images.append(image)
DispatchQueue.main.async {
let attachImage = self.images[self.images.count - 1]
//Caculate new size
let newImageWidth = (self.tvContent.bounds.size.width)
let scale = newImageWidth/image.size.width
let newImageHight = image.size.height*scale
let attachment = NSTextAttachment()
attachment.bounds = CGRect.init(x: 0, y: 0, width: newImageWidth, height: newImageHight)
attachment.image = attachImage
var attributedString: NSMutableAttributedString!
attributedString = NSMutableAttributedString(attributedString: self.tvContent.attributedText)
let attachString = NSAttributedString(attachment: attachment)
// self.tvContent.textStorage.insert(
// attachString,
// at: self.tvContent.selectedRange.location)
attributedString.append(attachString)
self.tvContent.attributedText = attributedString
}
}
}
}
}