Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add image in UITextView? [duplicate]

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)
like image 594
Daniel Avatar asked Sep 13 '25 09:09

Daniel


1 Answers

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)
like image 78
Ashish Thakkar Avatar answered Sep 16 '25 01:09

Ashish Thakkar