How To Create a UIButton in xCode With Two Lines of Text and Centered
Simply using Interface Builder, I could not find a way to make my buttons center multiple lines of text. If there is a super easy way, then let me know and I’ll update this post (but I don’t currently think there is). So I figured out how to do it programmatically, which is what I’m showing here in this post.
Go ahead and create your button using Interface Builder (or programmatically). If you use Interface Builder, then make sure you create the IBOutlets in the header file and appropriately link those attributes to the UIButtons in Interface Builder.
Once you’ve got the buttons created and linked, you’re ready to set the text for the button labels. To center the text you’ll need to use:
myCustomButton.titleLabel.textAlignment = UITextAlignmentCenter;
And to set the text so that it appears in two lines you’ll need to use:
[myCustomButton setTitle:@"theTopText\nBottomText" forState:UIControlStateNormal];
“myCustomButton” would be replaced by whatever name you’ve given your UIButton. Obviously you can use dot syntax or [brackets] for either line.
Notice that the “\n” is used as a line break so that your button label will read “the Top Text” on the top and “Bottom Text” below it. Both will be centered as a result of you setting the text alignment.
Here is a snippet of my code and the resulting buttons:







