2016-07-20 39 views
2

私はメモを取っていますが、問題が発生しました。UITextViewでイメージを追加するにはどうすればよいですか?

UITextViewに画像を入れたいと思います。私はUITextViewに画像を配置するNSAttributedStringを使用しますが、私はimagepickerから画像を入れたときに、画像の大きさは、私はリンゴのようにそれを作りたい、この

image

のような大きすぎるアプリ

ノート

image2

これはどのようにしてわかりますか?

let images = selectedImage 
    let attachment = NSTextAttachment() 

    attachment.image = images 

    let attString = NSAttributedString(attachment: attachment) 

    textView.textStorage.insertAttributedString(attString, atIndex: textView.selectedRange.location) 

答えて

2

これは

let textView = UITextView(frame: CGRectMake(50, 50, 200, 300)) 
let attributedString = NSMutableAttributedString(string: "before after") 
let textAttachment = NSTextAttachment() 
textAttachment.image = UIImage(named: "sample_image.jpg")! 

let oldWidth = textAttachment.image!.size.width; 

let scaleFactor = oldWidth/(textView.frame.size.width - 10); //for the padding inside the textView 
textAttachment.image = UIImage(CGImage: textAttachment.image!.CGImage, scale: scaleFactor, orientation: .Up) 
var attrStringWithImage = NSAttributedString(attachment: textAttachment) 
attributedString.replaceCharactersInRange(NSMakeRange(6, 1), withAttributedString: attrStringWithImage) 
textView.attributedText = attributedString; 
self.view.addSubview(textView) 
+0

おかげで、あなたに役立つかもしれません!できます!!しかし** NSAttributedString **を** NSUserDefaults **に保存すると、再度読み込むと画像サイズが大きくなります!! – Daniel

+0

@ダニエル..私も同じ問題に直面しています。解決策は何でしたか? – iOS

+0

この回答を見るhttp://stackoverflow.com/a/30417310/2564702 –

関連する問題