一応、こんな感じで動作しました。どうでしょうか?
let textView = UITextView()
let attributedString = NSMutableAttributedString(string: "before after")
let textAttachment = NSTextAttachment()
textAttachment.image = UIImage(named: "test.png")!
let oldWidth = textAttachment.image!.size.width;
let scaleFactor = oldWidth / (textView.frame.size.width - 10); //for the padding inside the textView
textAttachment.image = UIImage.init(cgImage: textAttachment.image!.cgImage!, scale: scaleFactor, orientation: UIImageOrientation.up)
let attrStringWithImage = NSAttributedString(attachment: textAttachment)
attributedString.replaceCharacters(in: NSMakeRange(6, 1), with: attrStringWithImage)
textView.attributedText = attributedString
let attrText = textView.attributedText
do {
let file = try attrText?.fileWrapper(from: NSRange(location: 0, length: (attrText?.length)!), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtfd])
saveData(data: file!)
} catch {
///
}
func saveData(data: FileWrapper){
let file_name = "test.rtfd"
if let dir = FileManager.default.urls( for: .documentDirectory, in: .userDomainMask ).first {
let path_file_name = dir.appendingPathComponent( file_name )
do {
try data.write(to: path_file_name, options: .atomic, originalContentsURL: nil)
} catch {
//エラー処理
}
}
}
参考にした情報
Convert NSAttributedString into Data for storage
How can I save the attributed string (text) into file (swift, cocoa)?
How can I add image in UITextView? [duplicate]
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/08/11 22:59 編集