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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With