How to get/set attributes of attributedString (from Text Layer)?

Hi! I’m on Sketch 2025.2.1 (Barcelona) and I’m trying write plugin code for getting and setting the text in TextLayers, for localization purposes. I’ve got that working fine, but now I also need to get/set the internal styling (mainly bold/italic and color) of individual text-ranges inside a string.

I’ve found out that string-internal styling is stored as attributedString with attributes in the Sketch (JSON) Open File Format, but I’m looking for a way to access this data from JavaScript code.

A sketch.Types.Text layer does not seem to have direct access to this data. But I can use layer.sketchObject to get the underlying native MSTextLayer object, and from that I can use .attributedString() to get the MSAttributedText object, which also gives me the text-string via its method .string().

However, then I’m stuck, since from there I don’t know how to access the array of stringAttribute (?) objects which I suppose contain attributes of type MSAttributedStringFontAttribute and MSAttributedStringFontColorAttribute etc.

Any help would be appreciated.

Never mind, I was able to solve it by using “introspection” methods on the Mocha class.

I can access the text-styling ranges this way, from a Text component (layer) :

msTextLayer = textComponent.sketchObject // MSTextLayer
msAttribStr = msTextLayer.attributedString() // MSAttributedString
strAttribs = msAttribStr.attributedStringAttributes() // MSAttributedStringAttribute
attribs = Array.from(strAttribs)

attr = attribs[0]
r = attr.range()
d = attr.attributeDictionary()
//k = d.allKeys()

c = d["MSAttributedStringColorAttribute"]

f = d["MSAttributedStringFontAttribute"]
fd = f.fontAttributes()
//fk = fd.allKeys()
fn = fd["NSFontNameAttribute"]
1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.