Search code examples
iosregexswiftnsmutableattributedstring

replace specific text to the image using NSMutableAttributedString and regex


I want to replace "[img src=(IMAGE NAME)]" text to (IMAGE NAME) image. but text replaced with blank. not an image. what should i do?

    guard
        let original = self.text
        else { return }
    let pattern = "\\[img src=(\\w+)\\]"

    do{
        let regex = try NSRegularExpression(pattern: pattern, options: [])
        let matches = regex.matches(in: original, options : [], range : NSMakeRange(0, original.characters.count))
        let attributeString = NSMutableAttributedString(string : original)

        for match in matches.reversed(){
            let emoticon = attributeString.attributedSubstring(from: match.rangeAt(1)).string

            if let image = UIImage(named : "\(emoticon)"){
                let attributedImage = NSTextAttachment()
                attributedImage.image = image
                attributedImage.bounds = CGRect(x : 0, y : 0, width : image.size.width, height : image.size.height)
                attributeString.replaceCharacters(in: match.rangeAt(0), with: NSAttributedString(attachment: attributedImage))
            }
        }

        self.attributedText = attributeString
    }catch{

    }

Solution

  • I solved this problem. NSTextAttachment with Image cannot display in UITextField. but, In UITextView with edit mode, can display the Image.