Search code examples
iosswifthyperlinkemojinsmutableattributedstring

How to add NSLinkAttributeName to emoji?


I am trying to use emoji as a link.

emojiString.addAttribute(NSLinkAttributeName, value: "https://www.google.com/" , range: NSMakeRange(0,1))

The code above turns the emoji into a link but the emoji will disappear.


Solution

  • The cause of your issue may be this:

    NSMakeRange(0,1)
    

    Many Cocoa/Cocoa Touch APIs use UTF-16 based offsets & counts.

    And most emojis are made of 2 UTF-16 code units, some others 4 or more.

    If you want to make a range indicating the first character of emojiString.string, and make it a link, you may need to write something like this:

    if let ch = emojiString.string.characters.first {
        let range = NSRange(0..<String(ch).utf16.count)
        emojiString.addAttribute(NSLinkAttributeName, value: "https://www.google.com/" , range: range)
    }