Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SKLabelNode: Possible to insert NSTextAttachment or icon into block of text?

I have a SKLabelNode which has a string that I'd like to replace with an icon.

let attachment = NSAttributedString(attachment: txt)
attributedString.replaceCharacters(in: NSRange(location: range.location, length: range.length), with: attachment)

But when actually outputted, there's nothing there! The characters are successfully removed, but no text attachment is inserted. attachmentBounds is also not called when I try to subclass NSTextAttachment.

My question: is there some trick to getting this working or a better way to place an icon within a block of text while using SpriteKit?

like image 841
Dandy Avatar asked Dec 04 '25 08:12

Dandy


1 Answers

Just ran into the same problem, and with some searching on stack overflow, decided to use the SKSpriteNode child solution.

if let attributedText = _labelnode.attributedText {
  attributedText.enumerateAttribute(NSAttributedString.Key.attachment, in: NSRange(location: 0, length: attributedText.length), options: []) { (value, range, stop) in
        if value is NSTextAttachment {
            if let attachment = value as? NSTextAttachment,
                let image = attachment.image {
                if let tintedImage = image.tinted(with: legendEntry.colour) {
                    let texture = SKTexture(image: tintedImage)
                    let imageSpriteNode = SKSpriteNode(texture: texture)
                    _labelnode.addChild(imageSpriteNode)
                }
            }
        }
    }
}

Will need to position and shrink image accordingly.

like image 98
swainwri Avatar answered Dec 07 '25 05:12

swainwri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!