如何在UITextView中添加图像? [重复]

时间:2021-08-07 07:28:11

This question already has an answer here:

这个问题在这里已有答案:

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

我想在UITextView中放置一个图像。我使用NSAttributedString将图像放在UITextView中但是当我从图像拾取器中放入图像时,图像大小太大了

如何在UITextView中添加图像? [重复]

I want to make it like the apple notes app

我想让它像苹果笔记应用程序

如何在UITextView中添加图像? [重复]

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)

1 个解决方案

#1


2  

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)

#1


2  

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)