The default appearance of UIButton is a single line text, but it also supports a multi-line text with some minor tweak.
To make a multi-line text in UIButton, you insert a new line character (
\n) wherever you want in button title and set
let button = UIButton(type: .system)
button.setTitle("Title\nSubtitle", for: .normal)
button.titleLabel?.lineBreakMode = .byWordWrapping
You can adjust text alignment with
let buttonCenter = UIButton(type: .system)
buttonCenter.setTitle("Title\nSubtitle", for: .normal)
buttonCenter.titleLabel?.lineBreakMode = .byWordWrapping
buttonCenter.titleLabel?.textAlignment = .center
let buttonRight = UIButton(type: .system)
buttonRight.setTitle("Title\nSubtitle", for: .normal)
buttonRight.titleLabel?.lineBreakMode = .byWordWrapping
buttonRight.titleLabel?.textAlignment = .right
You can achieve the same effect on the storyboard. Under Attributes inspector, set title with a new line character, and Line Break to Word Wrap.
But you can't adjust text alignment with Plain title. To change text alignment:
- Change the title to Attributed.
- Select all the text in the text field.
- Then select text alignment that you want.
Read more article about Swift, UIKit, or see all available topic
Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.
If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.Become a patron Tweet Share
History of Auto Layout constraints
Learn different ways to define Auto Layout constraints programmatically.
How to split a string into an array of substrings in Swift
Learn different ways to split a string into an array of substrings.