47

I want to add both text and image in UITextView. The textview should be expanded according to the length of the text and image. In short what I want to do is that when I capture an image from camera or pick from gallery then it should display in UITextView and I should also be able to add some text with that image similar to Facebook.I am also attaching an image that how the UITextView will look like.

enter image description here

2

10 Answers 10

85

This is absolutely possible now, using

+ (NSAttributedString *)attributedStringWithAttachment:(NSTextAttachment *)attachment

See Apple docs here

And this example taken from this other answer:

UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0,0,140,140)];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"before after"];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:@"sample_image.jpg"];

CGFloat oldWidth = textAttachment.image.size.width;

//I'm subtracting 10px to make the image display nicely, accounting
//for the padding inside the textView
CGFloat scaleFactor = oldWidth / (textView.frame.size.width - 10);
textAttachment.image = [UIImage imageWithCGImage:textAttachment.image.CGImage scale:scaleFactor orientation:UIImageOrientationUp];
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attributedString replaceCharactersInRange:NSMakeRange(6, 1) withAttributedString:attrStringWithImage];
textView.attributedText = attributedString;

Using the above code will get you an image with text inside a UITextView on iOS 7+. You can/show style the attributed text as you want it and probably set the width of the image to make sure it fits within your textView (as well as setting your own aspect ratio/scale preference)

Here's a quick test image:

enter image description here

2
  • How i can add 2 or 3 images?. Currenlty replace the same position
    – jose920405
    Nov 14, 2015 at 17:39
  • well, you could insert at a specific index using the code you supplied in your answer (??) or, you could add more spaces here between text and replace each of those added spaces. Really, I rather like your answer for your issue.
    – d2burke
    Nov 23, 2015 at 16:04
40

Thank you for your code, it actually worked. I make a code in the Swift, so I would like to share Swift version of your code. I checked this code works too.

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;

//I'm subtracting 10px to make the image display nicely, accounting
//for the padding inside the textView
let scaleFactor = oldWidth / (textView.frame.size.width - 10);
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)

Code For Swift 3.0

var attributedString :NSMutableAttributedString!
attributedString = NSMutableAttributedString(attributedString:txtBody.attributedText)
let textAttachment = NSTextAttachment()
textAttachment.image = image

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

//I'm subtracting 10px to make the image display nicely, accounting
//for the padding inside the textView

let scaleFactor = oldWidth / (txtBody.frame.size.width - 10);
textAttachment.image = UIImage(cgImage: textAttachment.image!.cgImage!, scale: scaleFactor, orientation: .up)
let attrStringWithImage = NSAttributedString(attachment: textAttachment)
attributedString.append(attrStringWithImage)
txtBody.attributedText = attributedString;
3
  • Thanks. It helped me. Feb 27, 2017 at 11:48
  • Can we add TextAttachment image as background of UItextView @KoheiArai
    – Mansuu....
    Dec 15, 2017 at 13:15
  • could you explain NSMakeRange? Mar 22, 2021 at 10:42
15

if you just want place the image in the end, you can use

//create your UIImage
let image = UIImage(named: change_arr[indexPath.row]);
//create and NSTextAttachment and add your image to it.
let attachment = NSTextAttachment()
attachment.image = image
//put your NSTextAttachment into and attributedString
let attString = NSAttributedString(attachment: attachment)
//add this attributed string to the current position.
textView.textStorage.insertAttributedString(attString, atIndex: textView.selectedRange.location)

Check This answer

5

if you want to get the image from the camera, you can try my code below: (Swift 3.0)

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    //create and NSTextAttachment and add your image to it.
    let attachment = NSTextAttachment()
    attachment.image = image
    //calculate new size.  (-20 because I want to have a litle space on the right of picture)
    let newImageWidth = (textView.bounds.size.width - 20 )
    let scale = newImageWidth/image.size.width
    let newImageHeight = image.size.height * scale
    //resize this
    attachment.bounds = CGRect.init(x: 0, y: 0, width: newImageWidth, height: newImageHeight)
    //put your NSTextAttachment into and attributedString
    let attString = NSAttributedString(attachment: attachment)
    //add this attributed string to the current position.
    textView.textStorage.insert(attString, at: textView.selectedRange.location)
    picker.dismiss(animated: true, completion: nil)
}
4
  • Can you tell me how to push the cursor to the end of the image so that user can continue typing further?
    – Vasanth
    Dec 29, 2017 at 9:05
  • You can try this code to move cursor to the end of text: let newPosition = textField.endOfDocument textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition) Dec 30, 2017 at 16:24
  • 1
    more information you can read at this link: stackoverflow.com/questions/34922331/… Dec 30, 2017 at 16:26
  • Perfect code... Now how can I read back attributedstring with image back in textbeginediting method??
    – karan
    Mar 29, 2018 at 11:35
2

Lots of people are making this a lot more complicated than it needs to be. Firstly, add your image to the catalogue at the right size:

Twitter logo image

Then, create the NSAttributedString in code:

// Creates the logo image
let twitterLogoImage    = NSTextAttachment()
twitterLogoImage.image  = UIImage(named: "TwitterLogo")
let twitterLogo         = NSAttributedString(attachment: twitterLogoImage)

Then add the NSAttributedString to what you want:

// Create the mutable attributed string
let text = NSMutableAttributedString(string: "")

/* Code above, creating the logo */
/*    More attributed strings    */

// Add the logo to the whole text
text.append(twitterLogo)
textView.attributedText = text

Or:

textView.attributedText = twitterLogo
0
let htmlString = "<html><body><h1>This is the title</h1><p>This is the first paragraph.</p><img src=\"https://miro.medium.com/max/9216/1*QzxcfBpKn5oNM09-vxG_Tw.jpeg\" width=\"360\" height=\"240\"><p>This is the second paragraph.</p><p>This is the third paragraph.</p><p>This is the fourth paragraph.</p><p>This is the last paragraph.</p></body></html>"

Use this string extension:

extension String {
    func convertToAttributedFromHTML() -> NSAttributedString? {
        var attributedText: NSAttributedString?
        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue]
        if let data = data(using: .unicode, allowLossyConversion: true), let attrStr = try? NSAttributedString(data: data, options: options, documentAttributes: nil) {
            attributedText = attrStr
        }
        return attributedText
    }
}

Then set the textView:

textView.attributedText = htmlString.convertToAttributedFromHTML()
0

If you want to add a simple image in textview from Gallery or Camera as an attachment then this method should be used:

   func insertImage(_ image:UIImage) {
    let attachment = NSTextAttachment()
    attachment.image = image
    attachment.setImageHeight(height: 200)
    let attString = NSAttributedString(attachment: attachment)
    /// at is current cursor position
    self.descriptionTextView.textStorage.insert(attString, at: self.descriptionTextView.selectedRange.location)
    descriptionTextView.font = UIFont(name: UIFont.avenirNextRegular, size: 17)
    descriptionTextView.textColor = .white
}

If you want to add an image from a link than you need to do this, there can be multiple links in string, so will be achive using these methods.

Checks URLS from exisiting string so that we can download an image and show as attachment

func checkForUrls(text: String) -> [NSTextCheckingResult] {
    let types: NSTextCheckingResult.CheckingType = .link

    do {
        let detector = try NSDataDetector(types: types.rawValue)

        let matches = detector.matches(in: text, options: .reportCompletion, range: NSRange(location: 0, length: text.count))
        return matches
     //   return matches.compactMap({$0.url})
    } catch let error {
        debugPrint(error.localizedDescription)
    }

    return []
}

// Recursive funtion call next after successfull downloaded

func convertToAttachment() {
    if imageURLResultsFromStr.count > 0 {
        imageTOAttributedText(imageURLResultsFromStr.first?.url, imageURLResultsFromStr.first?.range)
    }
}

**// MARK: Server URL to Image conversion to show**
func imageTOAttributedText(_ url:URL?,_ range:NSRange?) {
    guard let url = url, let range = range else { return }
    let imgView = UIImageView()

   imgView.kf.setImage(with: url, completionHandler: { result in
        switch result {
        case .success(var data):
            let attachment = NSTextAttachment()
            data.image.accessibilityIdentifier  = self.recentlyUploadedImage
            attachment.image = data.image
           // attachment.fileType = self.recentlyUploadedImage
            attachment.setImageHeight(height: 200)

            /// This will help to remove existing url from server which we have sent as url
            /// Start
            let mutStr = self.descriptionTextView.attributedText.mutableCopy() as! NSMutableAttributedString
            let range = (mutStr.string as NSString).range(of: "\n\(url.absoluteString)\n")
            mutStr.deleteCharacters(in: range)
            self.descriptionTextView.attributedText = mutStr
                //End

            /// Add image as attachment downloaded from url
            let attString = NSAttributedString(attachment: attachment)
            self.descriptionTextView.textStorage.insert(attString, at: range.location)
            /// Recursivly calls to check how many urls we have in string to avoid wrong location insertion
            /// We need to re-calculate new string from server after removing url string and add image as attachment
            self.imageURLResultsFromStr.remove(at: 0)
            self.imageURLResultsFromStr =  self.checkForUrls(text: self.descriptionTextView.text)
            self.convertToAttachment()
        case .failure(let error):
            print(error)
        }
    })
}

// Now call this function and initialise it from server string, Call it from viewdidload or from api response

  func initialise() {
    self.descriptionTextView.text = ..string from server
    self.imageURLResultsFromStr =  self.checkForUrls(text:string from server)
    convertToAttachment()
      }
var imageURLResultsFromStr:[NSTextCheckingResult] = []
-2
         NSURL *aURL = [NSURL URLWithString:[[NSString stringWithFormat:@"%@%@",Image_BASE_URL,str] stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
        //UIImage *aImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:aURL]];
        //[aImage drawInRect:CGRectMake(0, 0, 20, 20)];


        __block  NSTextAttachment *imageAttachment = [NSTextAttachment new];
        imageAttachment.bounds = CGRectMake(0, -5, 20, 20);
        NSAttributedString *stringWithImage = [NSAttributedString attributedStringWithAttachment:imageAttachment];
        [deCodedString replaceCharactersInRange:NSMakeRange(deCodedString.length, 0) withAttributedString:stringWithImage];
        incomingMessage.messageAttributedString = deCodedString;


        SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
        imageAttachment.image = [UIImage imageNamed:@"profile_main_placeholder"];

        [downloader downloadImageWithURL:aURL
                                 options:0
                                progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                                    // progression tracking code
                                }
                               completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                                   if (image && finished) {
                                       [image drawInRect:CGRectMake(0, 0, 20, 20)];
                                       imageAttachment.image = image;

                                       dispatch_async(dispatch_get_main_queue(), ^(void)
                                                      {

                                                          [self.tbl_Conversation reloadRowsAtIndexPaths:[self.tbl_Conversation indexPathsForVisibleRows]
                                                                                       withRowAnimation:UITableViewRowAnimationNone];
                                                          [self.tbl_Conversation reloadData];
                                                      });



                                       //                                                              NSAttributedString *stringWithImage = [NSAttributedString attributedStringWithAttachment:imageAttachment];
                                       //                                                              [deCodedString replaceCharactersInRange:NSMakeRange(deCodedString.length, 0) withAttributedString:stringWithImage];
                                       //                                                              incomingMessage.messageAttributedString = deCodedString;
                                   }
                               }];
1
  • Check above answer that change the image in textview after downloading an image Apr 22, 2016 at 9:53
-2

Please, try use placeholderTextView to simple input with icon placeholder support.

@IBOutlet weak var tvMessage: PlaceholderTextView!

let icon: NSTextAttachment = NSTextAttachment()
icon.image = UIImage(named: "paper-plane")
let iconString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: icon))

tvMessage.icon = icon

let textColor = UIColor.gray
let lightFont = UIFont(name: "Helvetica-Light", size: tvMessage.font!.pointSize)
let italicFont = UIFont(name: "Helvetica-LightOblique", size: tvMessage.font!.pointSize)
let message = NSAttributedString(string: " " + "Personal Message", attributes: [ NSFontAttributeName: lightFont!,   NSForegroundColorAttributeName: textColor])
iconString.append(message)
let option = NSAttributedString(string: " " + "Optional", attributes: [ NSFontAttributeName: italicFont!, NSForegroundColorAttributeName: textColor])
iconString.append(option)

tvMessage.attributedPlaceHolder = iconString

tvMessage.layoutSubviews()
0
-2

You can refer to how MLLabel work. Main ideal is NSTextAttachment

  • Create ImageAttachment extends NSTextAttachment -> override - (nullable UIImage *)imageForBounds:(CGRect)imageBounds textContainer:(nullable NSTextContainer *)textContainer characterIndex:(NSUInteger)charIndex to return image size like you want.
  • Create NSAttributedString with [NSAttributedString attributedStringWithAttachment:ImageAttachment]
  • Create NSMutableAttributedString and append attributed string of ImageAttachment using - (void)replaceCharactersInRange:(NSRange)range withAttributedString:(NSAttributedString *)attrString;
  • Result: You have NSMutableAttributedString contain your image and set it to textView.attributedText

Sample: HERE

2
  • Hi thanks for your answer and welcome to StackOverflow. Your answer would be improved if it explained how MLLabel worked in some detail. Links to other sites are fine, but mainly to support your answer.
    – Alex Young
    Mar 24, 2017 at 1:53
  • Updated answer. Thanks all!
    – ducnm.isbk
    Mar 24, 2017 at 6:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.