Last active
August 29, 2015 14:19
-
-
Save kumo/eb6e2993874cf780afc3 to your computer and use it in GitHub Desktop.
Experimenting with replacing text in a Sketch document
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var replaceValues = function(string, values) { | |
var newString = string; | |
for (var i=0; i < values.length; i++) { | |
var stringToken = "["+(i+1)+"]"; | |
newString = newString.replace(stringToken, values[i]); | |
} | |
return newString; | |
} | |
var values = [ | |
["Cat", "miao"], | |
["Dog", "woof"], | |
["Quokka", "??"] | |
]; | |
var template = context.selection[0]; | |
var frame = template.frame() | |
var width = frame.width() | |
var height = frame.height() | |
for (var rowId=0; rowId < values.length; rowId++) { | |
var rowValues = values[rowId]; | |
var instance = template.duplicate(); | |
var instanceFrame = instance.frame() | |
instanceFrame.addX((width + 30) * (rowId + 1)) | |
// change the artboard/layer name | |
var newName = replaceValues(instance.name(), rowValues); | |
instance.setName(newName); | |
var labels = instance.children(); | |
for (var labelId=0; labelId < labels.length(); labelId++) { | |
var label = labels[labelId]; | |
if (! [label isKindOfClass:[MSTextLayer class]]) { | |
continue | |
} | |
var existingText = label.stringValue() | |
var newText = replaceValues(existingText, rowValues); | |
label.setStringValue(newText) | |
// reset name, so that the displayed string is update | |
var name = label.name() | |
label.setName(newText) | |
label.setName(name) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment