заменить NSTextAttachment, который включает изображение, на String

Ранее я изменил определенные строки на NSTextAttachment, которые включают изображение для отображения пользовательского смайлика.

Строка для кода NSTextAttachment

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

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

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

            if  let emoticonAndroid = Emoticon(rawValue: emoticonString),
                let image = UIImage(named : "\(emoticonAndroid.convertFromAndroid().rawValue)_000"){
                image.accessibilityIdentifier = emoticonAndroid.rawValue
                let attributedImage = NSTextAttachment()
                attributedImage.image = image
                attributedImage.bounds = CGRect(x: 0, y: -8, width: 25, height: 25)
                attributeString.beginEditing()
                attributeString.replaceCharacters(in: match.rangeAt(0), with: NSAttributedString(attachment: attributedImage))
                attributeString.endEditing()
            }
        }

        self.attributedText = attributeString
    }catch{
        return
    }

}

но мне нужно заменить NSTextAttachment на строку для отправки сообщения. Я использовал метод NSMutableAttributedString.replaceCharacters(in:with:). но он может работать только с одним изображением смайлика.

один смайлик два смайлика или более

как я могу это исправить?

NSTextAttachment к строковому коду

{
    if let original = self.attributedText{
        let attributeString = NSMutableAttributedString(attributedString: original)

        original.enumerateAttribute(NSAttachmentAttributeName, in: NSMakeRange(0, original.length), options: [], using: { attribute, range, _ in
            if let attachment = attribute as? NSTextAttachment,
                let image = attachment.image{
                let str = "[img src=\(image.accessibilityIdentifier!)]"

                attributeString.beginEditing()
                attributeString.(in: range, with: str)
                attributeString.endEditing()
            }
        })

        self.attributedText = attributeString
        return attributeString.string
    }else{
        return nil
    }
}

person ltewarp0lleh    schedule 05.08.2017    source источник


Ответы (1)


Хм.. Я решил эту проблему.

Первый: подсчитать количество NSTextAttachment

var count = 0
    self.attributedText.enumerateAttribute(NSAttachmentAttributeName, in : NSMakeRange(0, self.attributedText.length), options: [], using: { attribute, range, _ in
        if let attachment = attribute as? NSTextAttachment,
            let image = attachment.image{
            count = count + 1
        }
    })
    return count

Второе: замените NSTextAttachment на String и рассчитайте измененный диапазон. <- Повторение

for i in 0..<self.countOfNSTextAttachment(){
        let attributedString = NSMutableAttributedString(attributedString: self.attributedText)
        var count = 0
        attributedString.enumerateAttribute(NSAttachmentAttributeName, in : NSMakeRange(0, attributedString.length), options: [], using: { attribute, range, _ in
            if let attachment = attribute as? NSTextAttachment,
                let image = attachment.image{
                let str = "[img src=\(image.accessibilityIdentifier!)]"

                if count == 0{
                    attributedString.beginEditing()
                    attributedString.replaceCharacters(in: range, with: NSAttributedString(string : str))
                    attributedString.endEditing()
                    self.attributedText = attributedString
                }else{
                    return
                }
                count = count + 1
            }
        })
    }

    return self.attributedText.string

Результат: результат

Идеальный!!

person ltewarp0lleh    schedule 06.08.2017
comment
Используйте options: .reverse, чтобы избежать цикла for (и не перепутать диапазоны) и пропустить первый фрагмент кода. - person Botond Magyarosi; 28.05.2019