4

I'm making a note taking app but I ran into trouble.

I want to put a image in UITextView. I used NSAttributedString to put the image in UITextView but when I put image from the imagepicker, the image size is too big like this

image

I want to make it like the apple notes app

image2

How can I figure that?

   let images = selectedImage
   let attachment = NSTextAttachment()

   attachment.image = images

   let attString = NSAttributedString(attachment: attachment)

   textView.textStorage.insertAttributedString(attString, atIndex: textView.selectedRange.location)
Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
Daniel
  • 521
  • 1
  • 7
  • 16

1 Answers1

6

This might be helpful to you

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)
Ashish Thakkar
  • 944
  • 8
  • 27