0

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{

    }
ltewarp0lleh
  • 73
  • 1
  • 7

2 Answers2

0

ou can't do this. Neither in swift nor objective-c.

The thing to do is to store the data you want to retrieve. That is... store the name somewhere and use that to load the image. Not the other way around.

So create a property something like imageName and then use that as image name.

0

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

ltewarp0lleh
  • 73
  • 1
  • 7