Forum Archive

How to add a new line in a button title

sskaye

I'd like to have my button title wrap over two lines. Normally, I'd use the newline character in a text string (e.g. 'Line1 \n Line2'), but that doesn't work here.

Is there any way to insert a newline or have the text wrap?

Thanks.

sskaye

Sorry, forgot to add that I made the button and am editing the title in the UI editor.

dgelessus

By default, iOS buttons only allow a single line of text, any extra lines are silently hidden. Pythonista's ui.Button uses this default behavior and doesn't provide a way to change that. You can use objc_util to change the behavior on the underlying label:

import objc_util
import ui

NSLineBreakByWordWrapping = 0
NSLineBreakByCharWrapping = 1
NSLineBreakByClipping = 2
NSLineBreakByTruncatingHead = 3
NSLineBreakByTruncatingTail = 4
NSLineBreakByTruncatingMiddle = 5 # Default for button labels.

b = ui.Button() # Your button (doesn't need to be created here, can come from somewhere else, like a UI file).
objc_util.ObjCInstance(b).button().titleLabel().setLineBreakMode(NSLineBreakByWordWrapping) # You can use any of the line break modes listed above.

Also, I'm not sure if the UI designer recognizes escape sequences like \n in button titles and such. If you see a literal \n appearing in the button title instead of a newline, try setting the button title in code (b.title = "line 1\nline 2") instead of in the UI designer.

sskaye

Worked perfectly. Thanks!