如何在 UITextView 中添加图像?

Dan*_*iel 4 uitextview uiimage ios swift

我正在制作一个笔记应用程序,但遇到了麻烦。

我想将图像放入UITextView中。我使用NSAttributedString将图像放入UITextView中,但是当我从 imagepicker 中放入图像时,图像大小太大,如下所示

图像

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

图片2

我怎么知道呢?

   let images = selectedImage
   let attachment = NSTextAttachment()

   attachment.image = images

   let attString = NSAttributedString(attachment: attachment)

   textView.textStorage.insertAttributedString(attString, atIndex: textView.selectedRange.location)
Run Code Online (Sandbox Code Playgroud)

Ash*_*kar 6

这可能对你有帮助

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)
Run Code Online (Sandbox Code Playgroud)