Search code examples
apitextsketch-3

Sketch API - Text styling


I have a lot of trouble with the Sketch API/Sketch API Documentation. What is the correct way to put some styling on a text (font-size, font-family, etc.)?

This is my text inside a loop.

 var text = group.newText(
        {
            text: Colors.groupNames[index],
            frame: new api.Rectangle(50, 0, 50, 50),
        }
    );

Solution

  • You should be able to do:

    var text = group.newText({font: NSFont.fontWithName_size("OpenSans-Bold", 15), text:"Hello World"})
    

    But there is a bug in the API, a workaround is to do:

    var text = group.newText({text: "Hello World"})
    text._object.setFont(NSFont.fontWithName_size("OpenSans-Bold", 15))
    

    The font name is the font filename without the extension. You can find them in ~/Library/Fonts.

    The other properties you can set on a text layer are listed here and here is an example from the docs:

    var text = group.newText({fixedWidth: true, alignment: NSTextAlignmentCenter, systemFontSize: 24, text:"Hello World"})
    text.frame = new sketch.Rectangle(0, 160, 200, 30) // adjust the frame last, after the font/size/alignment etc has been set up