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:@"theTopTextnBottomText" 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:




Note you must set the textAlignment before you set the title. Stupid iCrap!
My multi-line text of “line one n line two” just displays “line…two”.
I know my button, and connections… are working. (Otherwise I wouldn’t be able to change the text.)
(I don’t really care about the “alignment”.)
Everything is still trying to be displayed on 1 line.
(This is with IOS v3.1.3 as of Sept 2010.)
Try this:
[yourButton setLineBreakMode:UILineBreakModeCharacterWrap];
> setLineBreakMode:UILineBreakModeCharacterWrap
*PLEASE* put that into the original code.
None of this will ever work without it.
(I spent more than 2 hours on this non-working mess.)
UIButton setLineBreakMode: is deprecated as of iOS 3.0: Deprecated in iOS 3.0. Use the lineBreakMode property of the titleLabel instead.
Try this:
self.button.titleLabel.textAlignment = UITextAlignmentCenter;
self.button.titleLabel.lineBreakMode = UILineBreakModeCharacterWrap;
[self.button setTitle:@"First\nSecond" forState:UIControlStateNormal];
how to create a synchronous application on iphone?
You can add line breaks directly in Interface Builder by hitting opt+return while typing.