我正在尝试将包含nstextattachment的nsattributed字符串保存在核心数据中,但是在加载视图时,我要保存的数据未加载时并未保存
我已经在coredata中为带有图像的文本创建了一个可转换属性 我也将属性类型更改为子类中的nsattributed字符串
override func viewDidLoad() {
super.viewDidLoad()
detail = coreDataManager.shared.fetchTransactionDetail(transaction: parentTransaction!)
textView.attributedText = detail?.textWithImage
}
@IBAction func doneAction(_ sender: UIBarButtonItem) {
textView.resignFirstResponder()
doneButton.isEnabled = false
parentTransaction?.desc = textView.attributedText.string
detail?.setValue(self.textView.attributedText, forKey: "textWithImage")
coreDataManager.shared.saveContext()
}
let imagePickerController = UIImagePickerController()
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// Local variable inserted by Swift 4.2 migrator.
let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)
let image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage
let attachment = NSTextAttachment()
var scalingFactor = 1.0
let imageSize = image?.size
let width = textView.frame.size.width
if (width < imageSize!.width){
scalingFactor = Double((width)*CGFloat(scalingFactor) / imageSize!.width)
}
let rect = CGRect(x: 0, y: 0, width: imageSize!.width*CGFloat(scalingFactor), height: imageSize!.height*CGFloat(scalingFactor))
let newImage = UIImage(data: (image?.jpegData(compressionQuality: 0.1))!)
attachment.image = UIImage.resize(image: newImage!, targetSize: rect.size)
//calculate new size. (-20 because I want to have a litle space on the right of picture)
let newImageWidth = (textView.bounds.size.width - 50 )
scalingFactor = Double(newImageWidth/(image?.size.width)!)
let newImageHeight = (image?.size.height)! * CGFloat(scalingFactor)
//resize this
attachment.bounds = CGRect.init(x: 10, y: 0, width: newImageWidth, height: newImageHeight)
//put your NSTextAttachment into and attributedString
let attString = NSAttributedString(attachment: attachment)
//add this attributed string to the current position.
textView.textStorage.append(attString)
textView.font = UIFont(name: "Arial", size: 18)
picker.dismiss(animated: true, completion: nil)
}
coreDataManager.shared.createTupleDetail(text: "", image: self.image!.jpegData(compressionQuality: 0.1)! as NSData as Data, tuple: self.tupleCells[self.tupleCells.count-1])
它应该保存包含图像的文本,并在加载视图时再次加载 但它没有这样做。