Search code examples
swiftnsattributedstring

Swift String - How to replace a word with an image in a localized string?


in this app we have a localized string (more than 10 languages) and in this string there is a word "%1$s" which should be replaced by an image (a logo).

Having so many languages means that the word to be replaced (%1$s) is not always in the same position in the string.

In order to replace it with an image I tried this code:

// "%1$s" is contained in mystring to know where we should put the logo image
let myString = NSMutableAttributedString(string: "mylocalizedString")
        
// create our NSTextAttachment
let logoAttachment = NSTextAttachment()
logoAttachment = UIImage(named: "myLogoImage")
    
// wrap the attachment in its own attributed string so we can append it
let logoImageString = NSAttributedString(attachment: logoAttachment)
        
// Here I try to replace "%1$s" with the logo image
myString.mutableString.replacingOccurrences(of: "%1$s", with: logoImageString.string)
       
myLabel.attributedText = myString
myLabel.font = myFont
myLabel.textColor = myColor

But all I get is the localized string with still the "%1$s" word in there without the image of the logo.

Do I miss something?

Thanks a lot.


Solution

  • Solved as suggested by Larme in the comments:

    let range = myString.string.range(of: "%1$s")

    let nsRange = NSRange(range, in: myString.string)

    myString.replaceCharacters(in:range, with:logoImageString)