Another approach involves listing out all the attributes and their ranges.
let document = sketch.getSelectedDocument()
let text = document.selectedLayers.layers[0]
let attrStr = text.sketchObject.attributedStringValue()
let attributes = []
let block = __mocha__.createBlock_function('v40@?0@"NSDictionary"8{_NSRange=QQ}16^c32', (attrs,range,stop) => {
attributes.push({
"attributes": attrs,
"range": range
})
})
let range = NSMakeRange(0,attrStr.length())
attrStr.enumerateAttributesInRange_options_usingBlock(range,nil,block)
console.log(attributes)
Then depending on what part of the string you want to edit you can then also update the attributes and apply them to the layer.
let sketch = require('sketch')
let document = sketch.getSelectedDocument()
let text = document.selectedLayers.layers[0]
let attrStr = text.sketchObject.attributedStringValue()
let attributes = []
let block = __mocha__.createBlock_function('v40@?0@"NSDictionary"8{_NSRange=QQ}16^c32', (attrs,range,stop) => {
attributes.push({
"attributes": attrs,
"range": range
})
})
let range = NSMakeRange(0,attrStr.length())
attrStr.enumerateAttributesInRange_options_usingBlock(range,nil,block)
let newSubstr = "Hi"
// build a new substring from the attributes of the existing string that you want to use
let newAttrSubstr = NSAttributedString.new().initWithString_attributes(newSubstr,attributes[1].attributes)
let newAttrStr = NSMutableAttributedString.new().initWithAttributedString(attrStr)
// you'll need to know the range of the string that you are wanting to replace
newAttrStr.replaceCharactersInRange_withAttributedString(NSMakeRange(5,5),newAttrSubstr)
let colorSpace = document.sketchObject.colorSpace()
let sketchAttrString = MSAttributedString.alloc().initWithAttributedString_colorSpace_convert(newAttrStr,colorSpace,false)
sketchAttrString.attributedString = newAttrStr
text.sketchObject.setAttributedString(sketchAttrString)
I also figured out why Sketch was crashing from before. That's because that's because :setAttributedString
on the text layer is expecting a MSAttributedString
not a NSAttributedString
. Making one isn't too difficult.