使用 NSMutableAttributedString 和正则表达式将特定文本替换为图像

replace specific text to the image using NSMutableAttributedString and regex

我想将“[img src=(IMAGE NAME)]”文本替换为 (IMAGE NAME) 图片。 但文本替换为空白。不是图像。我该怎么办?

    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{

    }

你不能这样做。既不在 swift 也不在 objective-c.

要做的事情是存储要检索的数据。那就是......将名称存储在某处并使用它来加载图像。反之则不然。

因此创建一个 属性 类似 imageName 的名称,然后将其用作图像名称。

我解决了这个问题。带有图像的 NSTextAttachment 无法在 UITextField 中显示。但是,在具有编辑模式的 UITextView 中,可以显示图像。