How do you add multi-line text to a UIButton?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I have the following code...
UILabel *buttonLabel = [[UILabel alloc] initWithFrame:targetButton.bounds];
buttonLabel.text = @"Long text string";
[targetButton addSubview:buttonLabel];
[targetButton bringSubviewToFront:buttonLabel];
...the idea being that I can have multi-line text for the button, but the text is always obscured by the backgroundImage of the UIButton. A logging call to show the subviews of the button shows that the UILabel has been added, but the text itself cannot be seen. Is this a bug in UIButton or am I doing something wrong?
ios cocoa-touch uibutton uikit
add a comment |
I have the following code...
UILabel *buttonLabel = [[UILabel alloc] initWithFrame:targetButton.bounds];
buttonLabel.text = @"Long text string";
[targetButton addSubview:buttonLabel];
[targetButton bringSubviewToFront:buttonLabel];
...the idea being that I can have multi-line text for the button, but the text is always obscured by the backgroundImage of the UIButton. A logging call to show the subviews of the button shows that the UILabel has been added, but the text itself cannot be seen. Is this a bug in UIButton or am I doing something wrong?
ios cocoa-touch uibutton uikit
4
button.titleLabel?.numberOfLines = 0
– ma11hew28
May 12 '15 at 23:46
2
Note for this very very old QA, in modern Xcode VERY SIMPLY, CHOOSE "ATTRIBUTED TEXT" and then it's trivial, select "character wrap".
– Fattie
Dec 7 '16 at 15:05
Also see updated answer to a similar question.
– ToolmakerSteve
Mar 6 '17 at 0:11
add a comment |
I have the following code...
UILabel *buttonLabel = [[UILabel alloc] initWithFrame:targetButton.bounds];
buttonLabel.text = @"Long text string";
[targetButton addSubview:buttonLabel];
[targetButton bringSubviewToFront:buttonLabel];
...the idea being that I can have multi-line text for the button, but the text is always obscured by the backgroundImage of the UIButton. A logging call to show the subviews of the button shows that the UILabel has been added, but the text itself cannot be seen. Is this a bug in UIButton or am I doing something wrong?
ios cocoa-touch uibutton uikit
I have the following code...
UILabel *buttonLabel = [[UILabel alloc] initWithFrame:targetButton.bounds];
buttonLabel.text = @"Long text string";
[targetButton addSubview:buttonLabel];
[targetButton bringSubviewToFront:buttonLabel];
...the idea being that I can have multi-line text for the button, but the text is always obscured by the backgroundImage of the UIButton. A logging call to show the subviews of the button shows that the UILabel has been added, but the text itself cannot be seen. Is this a bug in UIButton or am I doing something wrong?
ios cocoa-touch uibutton uikit
ios cocoa-touch uibutton uikit
edited Aug 5 '17 at 20:19
Erik Godard
4,28952432
4,28952432
asked Mar 3 '09 at 0:22
Owain HuntOwain Hunt
2,43421610
2,43421610
4
button.titleLabel?.numberOfLines = 0
– ma11hew28
May 12 '15 at 23:46
2
Note for this very very old QA, in modern Xcode VERY SIMPLY, CHOOSE "ATTRIBUTED TEXT" and then it's trivial, select "character wrap".
– Fattie
Dec 7 '16 at 15:05
Also see updated answer to a similar question.
– ToolmakerSteve
Mar 6 '17 at 0:11
add a comment |
4
button.titleLabel?.numberOfLines = 0
– ma11hew28
May 12 '15 at 23:46
2
Note for this very very old QA, in modern Xcode VERY SIMPLY, CHOOSE "ATTRIBUTED TEXT" and then it's trivial, select "character wrap".
– Fattie
Dec 7 '16 at 15:05
Also see updated answer to a similar question.
– ToolmakerSteve
Mar 6 '17 at 0:11
4
4
button.titleLabel?.numberOfLines = 0
– ma11hew28
May 12 '15 at 23:46
button.titleLabel?.numberOfLines = 0
– ma11hew28
May 12 '15 at 23:46
2
2
Note for this very very old QA, in modern Xcode VERY SIMPLY, CHOOSE "ATTRIBUTED TEXT" and then it's trivial, select "character wrap".
– Fattie
Dec 7 '16 at 15:05
Note for this very very old QA, in modern Xcode VERY SIMPLY, CHOOSE "ATTRIBUTED TEXT" and then it's trivial, select "character wrap".
– Fattie
Dec 7 '16 at 15:05
Also see updated answer to a similar question.
– ToolmakerSteve
Mar 6 '17 at 0:11
Also see updated answer to a similar question.
– ToolmakerSteve
Mar 6 '17 at 0:11
add a comment |
25 Answers
25
active
oldest
votes
For iOS 6 and above, use the following to allow multiple lines:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
// you probably want to center it
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if you want to
[button setTitle: @"Line1nLine2" forState: UIControlStateNormal];
For iOS 5 and below use the following to allow multiple lines:
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
// you probably want to center it
button.titleLabel.textAlignment = UITextAlignmentCenter;
[button setTitle: @"Line1nLine2" forState: UIControlStateNormal];
2017, for iOS9 forward,
generally, just do these two things:
- choose "Attributed Text"
- on the "Line Break" popup select "Word Wrap"
5
Please note these assignments are deprecated in iOS 6. See the answer below by @NiKKi for the updated syntax.
– Aaron Brager
Jan 9 '13 at 22:36
3
Just so people know: this does not work if you're using NSAttributedString
– The dude
Oct 29 '13 at 12:08
22
Actually, just add button.titleLabel.numberOfLines = 0; That will make the lines unlimited. And button.titleLabel.textAlignment = NSTextAlignmentLeft; if you want left justified text as the title is centered by default.
– RyJ
Aug 21 '14 at 16:00
4
In swiftbutton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
– Robert
Jan 25 '15 at 17:36
1
Thanks @Robert for the swift solution. Can also use inference and omit theNSLineBreakMode
, like so:button.titleLabel?.lineBreakMode = .ByWordWrapping
.
– mjswensen
Aug 18 '15 at 22:49
|
show 3 more comments
The selected answer is correct but if you prefer to do this sort of thing in Interface Builder you can do this:
36
Thanks to my 24 year old self for writing this answer, from 28 year old self.
– Adam Waite
May 31 '18 at 22:16
3
And to stay with the Interface Builder only setup, one should settitleLabel.textAlignment
withNumber
value to1
inUser Defined Runtime Attributed
to make the text centered
– AnthoPak
Jun 14 '18 at 11:05
1
Thanks to your 28 year old self from my 24 year old self!
– Daniel Springer
Nov 22 '18 at 3:20
add a comment |
For IOS 6 :
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
As
UILineBreakModeWordWrap and UITextAlignmentCenter
are deprecated in IOS 6 onwards..
InsideNSText.h
in theFoundation
there is no deprecated added. Its available from 6.0 but not deprecated.
– Alex Cio
May 8 '15 at 11:42
In swift:button.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel?.textAlignment = NSTextAlignment.Center
– jcity
Dec 2 '15 at 0:56
add a comment |
If you want to add a button with the title centered with multiple lines, set your Interface Builder's settings for the button:
[]
Can you add a textual description of how to achieve this. An image is great, but if it becomes unavailable your answer will be useless.
– Rory McCrossan
Oct 21 '15 at 9:21
1
@RoryMcCrossan Hi, i added an image above. Can you view it? Please note, Xcode 7 is still buggy so button title might disappear. However, once you run the app you will get the desired result.
– user5440039
Oct 21 '15 at 10:03
2
This is the best answer in this thread, actually. Works immediately and shows centered text from IB. Thanks!
– RainCast
Oct 30 '16 at 23:00
@user5440039 Thanks for the great answer. There's no need to add a textual description.
– Fattie
Dec 7 '16 at 15:11
1
You made my day, thanks for pointing it out (y).
– Irfan
Apr 25 '17 at 8:03
add a comment |
To restate Roger Nolan's suggestion, but with explicit code, this is the general solution:
button.titleLabel?.numberOfLines = 0
add a comment |
SWIFT 3
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.setTitle("ButtonnTitle",for: .normal)
add a comment |
Left align on iOS7 with autolayout:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentLeft;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
add a comment |
There is a much easier way:
someButton.lineBreakMode = UILineBreakModeWordWrap;
(Edit for iOS 3 and later:)
someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
4
UIButton.lineBreakMode was deprecated in 3.0, so that's no longer a good option.
– Christopher Pickslay
Jan 17 '11 at 23:12
1
lineBreakMode is deprecated only as a direct property of UIButton. We are directed to "Use the lineBreakMode property of the titleLabel instead." I edited Valerii's answer accordingly. It's still a good option.
– Wienke
Oct 26 '12 at 18:57
add a comment |
First of all, you should be aware that UIButton already has a UILabel inside it. You can set it using –setTitle:forState:
.
The problem with your example is that you need to set UILabel's numberOfLines
property to something other than its default value of 1. You should also review the lineBreakMode
property.
I'm aware of the title property, but as far as I can tell it is impossible to set it to use more than one line, hence this approach. If I disable the backgroundImage, my UILabel show up, which to me suggests a bug in either bringSubviewToFront, or UIButton itself.
– Owain Hunt
Mar 3 '09 at 11:43
add a comment |
In Xcode 9.3 you can do it by using storyboard like below,
You need to set button title textAlignment to center
button.titleLabel?.textAlignment = .center
You don't need to set title text with new line (n) like below,
button.setTitle("GoodnAnswer",for: .normal)
Simply set title,
button.setTitle("Good Answer",for: .normal)
Here is the result,
myButton.titleLabel.textAlignment = NSTextAlignmentCenter
statement is also needed.
– tounaobun
Apr 12 at 11:53
add a comment |
For those who are using Xcode 4's storyboard, you can click on the button, and on the right side Utilities pane under Attributes Inspector, you'll see an option for Line Break. Choose Word Wrap, and you should be good to go.
This seems to work but it doesn't center when I tried it
– Matt Wolfe
Sep 12 '13 at 1:29
add a comment |
Answers here tell you how to achieve multiline button title programmatically.
I just wanted to add that if you are using storyboards, you can type [Ctrl+Enter] to force a newline on a button title field.
HTH
add a comment |
As to Brent's idea of putting the title UILabel as sibling view, it doesn't seem to me like a very good idea. I keep thinking in interaction problems with the UILabel due to its touch events not getting through the UIButton's view.
On the other hand, with a UILabel as subview of the UIButton, I'm pretty confortable knowing that the touch events will always be propagated to the UILabel's superview.
I did take this approach and didn't notice any of the problems reported with backgroundImage. I added this code in the -titleRectForContentRect: of a UIButton subclass but the code can also be placed in drawing routine of the UIButton superview, which in that case you shall replace all references to self with the UIButton's variable.
#define TITLE_LABEL_TAG 1234
- (CGRect)titleRectForContentRect:(CGRect)rect
{
// define the desired title inset margins based on the whole rect and its padding
UIEdgeInsets padding = [self titleEdgeInsets];
CGRect titleRect = CGRectMake(rect.origin.x + padding.left,
rect.origin.x + padding.top,
rect.size.width - (padding.right + padding.left),
rect.size.height - (padding.bottom + padding].top));
// save the current title view appearance
NSString *title = [self currentTitle];
UIColor *titleColor = [self currentTitleColor];
UIColor *titleShadowColor = [self currentTitleShadowColor];
// we only want to add our custom label once; only 1st pass shall return nil
UILabel *titleLabel = (UILabel*)[self viewWithTag:TITLE_LABEL_TAG];
if (!titleLabel)
{
// no custom label found (1st pass), we will be creating & adding it as subview
titleLabel = [[UILabel alloc] initWithFrame:titleRect];
[titleLabel setTag:TITLE_LABEL_TAG];
// make it multi-line
[titleLabel setNumberOfLines:0];
[titleLabel setLineBreakMode:UILineBreakModeWordWrap];
// title appearance setup; be at will to modify
[titleLabel setBackgroundColor:[UIColor clearColor]];
[titleLabel setFont:[self font]];
[titleLabel setShadowOffset:CGSizeMake(0, 1)];
[titleLabel setTextAlignment:UITextAlignmentCenter];
[self addSubview:titleLabel];
[titleLabel release];
}
// finally, put our label in original title view's state
[titleLabel setText:title];
[titleLabel setTextColor:titleColor];
[titleLabel setShadowColor:titleShadowColor];
// and return empty rect so that the original title view is hidden
return CGRectZero;
}
I did take the time and wrote a bit more about this here. There, I also point a shorter solution, though it doesn't quite fit all the scenarios and involves some private views hacking. Also there, you can download an UIButton subclass ready to be used.
add a comment |
You have to add this code:
buttonLabel.titleLabel.numberOfLines = 0;
add a comment |
It works perfectly.
Add to use this with config file like Plist, you need to use CDATA to write the multilined title, like this:
<string><![CDATA[Line1
Line2]]></string>
add a comment |
If you use auto-layout on iOS 6 you might also need to set the preferredMaxLayoutWidth
property:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
button.titleLabel.preferredMaxLayoutWidth = button.frame.size.width;
add a comment |
Setting lineBreakMode to NSLineBreakByWordWrapping (either in IB or code) makes button label multiline, but doesn't affect button's frame.
If button has dynamic title, there is one trick: put hidden UILabel with same font and tie it's height to button's height with layout; when set text to button and label and autolayout will make all the work.
Note
Intrinsic size height of one-line button is bigger than label's, so to prevent label's height shrink it's vertical Content Hugging Priority must be greater than button's vertical Content Compression Resistance.
add a comment |
If you use auto-layout.
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.numberOfLines = 2
add a comment |
These days, if you really need this sort of thing to be accessible in interface builder on a case-by-case basis, you can do it with a simple extension like this:
extension UIButton {
@IBInspectable var numberOfLines: Int {
get { return titleLabel?.numberOfLines ?? 1 }
set { titleLabel?.numberOfLines = newValue }
}
}
Then you can simply set numberOfLines as an attribute on any UIButton or UIButton subclass as if it were a label. The same goes for a whole host of other usually-inaccessible values, such as the corner radius of a view's layer, or the attributes of the shadow that it casts.
add a comment |
Roll your own button class. It's by far the best solution in the long run. UIButton and other UIKit classes are very restrictive in how you can customize them.
add a comment |
self.btnError.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
self.btnError.titleLabel?.textAlignment = .center
self.btnError.setTitle("Title", for: .normal)
add a comment |
swift 4.0
btn.titleLabel?.lineBreakMode = .byWordWrapping
btn.titleLabel?.textAlignment = .center
btn.setTitle( "Line1nLine2", for: .normal)
add a comment |
I incorporated jessecurry's answer within STAButton which is part of my STAControls open source library. I currently use it within one of the apps I am developing and it works for my needs. Feel free to open issues on how to improve it or send me pull requests.
add a comment |
I had an issue with auto-layout, after enabling multi-line the result was like this:
so the titleLabel
size doesn't affect the button size
I've added Constraints
based on contentEdgeInsets
(in this case contentEdgeInsets was (10, 10, 10, 10)
after calling makeMultiLineSupport()
:
hope it help you (swift 5.0):
extension UIButton {
func makeMultiLineSupport() {
guard let titleLabel = titleLabel else {
return
}
titleLabel.numberOfLines = 0
titleLabel.setContentHuggingPriority(.required, for: .vertical)
titleLabel.setContentHuggingPriority(.required, for: .horizontal)
addConstraints([
.init(item: titleLabel,
attribute: .top,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .top,
multiplier: 1.0,
constant: contentEdgeInsets.top),
.init(item: titleLabel,
attribute: .bottom,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .bottom,
multiplier: 1.0,
constant: contentEdgeInsets.bottom),
.init(item: titleLabel,
attribute: .left,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .left,
multiplier: 1.0,
constant: contentEdgeInsets.left),
.init(item: titleLabel,
attribute: .right,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .right,
multiplier: 1.0,
constant: contentEdgeInsets.right)
])
}
}
add a comment |
Although it's okay to add a subview to a control, there's no guarantee it'll actually work, because the control might not expect it to be there and might thus behave poorly. If you can get away with it, just add the label as a sibling view of the button and set its frame so that it overlaps the button; as long as it's set to appear on top of the button, nothing the button can do will obscure it.
In other words:
[button.superview addSubview:myLabel];
myLabel.center = button.center;
2
Please, if you suggest this kind of ugly approach at least don't make mistakes in your code example :). The label shouldn't have the same center as button if it's a subview. Use myLabel.frame = button.bounds; or myLabel.center = cgPointMake(button.frame.size.with*0.5,button.frame.size.height*0.5)
– JakubKnejzlik
Aug 6 '14 at 14:53
1
@GrizzlyNetch I'm specifically advising not to add it as a subview of the button.addSubview:
here adds it tobutton
's superview, thus making it a sibling of the button, so matching their centers is correct.
– Brent Royal-Gordon
Aug 8 '14 at 6:49
Ah, my mistake! You are right, I've missed the "small" fact it's in the superview :D ... sorry :)
– JakubKnejzlik
Aug 8 '14 at 8:16
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f604632%2fhow-do-you-add-multi-line-text-to-a-uibutton%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
25 Answers
25
active
oldest
votes
25 Answers
25
active
oldest
votes
active
oldest
votes
active
oldest
votes
For iOS 6 and above, use the following to allow multiple lines:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
// you probably want to center it
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if you want to
[button setTitle: @"Line1nLine2" forState: UIControlStateNormal];
For iOS 5 and below use the following to allow multiple lines:
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
// you probably want to center it
button.titleLabel.textAlignment = UITextAlignmentCenter;
[button setTitle: @"Line1nLine2" forState: UIControlStateNormal];
2017, for iOS9 forward,
generally, just do these two things:
- choose "Attributed Text"
- on the "Line Break" popup select "Word Wrap"
5
Please note these assignments are deprecated in iOS 6. See the answer below by @NiKKi for the updated syntax.
– Aaron Brager
Jan 9 '13 at 22:36
3
Just so people know: this does not work if you're using NSAttributedString
– The dude
Oct 29 '13 at 12:08
22
Actually, just add button.titleLabel.numberOfLines = 0; That will make the lines unlimited. And button.titleLabel.textAlignment = NSTextAlignmentLeft; if you want left justified text as the title is centered by default.
– RyJ
Aug 21 '14 at 16:00
4
In swiftbutton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
– Robert
Jan 25 '15 at 17:36
1
Thanks @Robert for the swift solution. Can also use inference and omit theNSLineBreakMode
, like so:button.titleLabel?.lineBreakMode = .ByWordWrapping
.
– mjswensen
Aug 18 '15 at 22:49
|
show 3 more comments
For iOS 6 and above, use the following to allow multiple lines:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
// you probably want to center it
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if you want to
[button setTitle: @"Line1nLine2" forState: UIControlStateNormal];
For iOS 5 and below use the following to allow multiple lines:
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
// you probably want to center it
button.titleLabel.textAlignment = UITextAlignmentCenter;
[button setTitle: @"Line1nLine2" forState: UIControlStateNormal];
2017, for iOS9 forward,
generally, just do these two things:
- choose "Attributed Text"
- on the "Line Break" popup select "Word Wrap"
5
Please note these assignments are deprecated in iOS 6. See the answer below by @NiKKi for the updated syntax.
– Aaron Brager
Jan 9 '13 at 22:36
3
Just so people know: this does not work if you're using NSAttributedString
– The dude
Oct 29 '13 at 12:08
22
Actually, just add button.titleLabel.numberOfLines = 0; That will make the lines unlimited. And button.titleLabel.textAlignment = NSTextAlignmentLeft; if you want left justified text as the title is centered by default.
– RyJ
Aug 21 '14 at 16:00
4
In swiftbutton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
– Robert
Jan 25 '15 at 17:36
1
Thanks @Robert for the swift solution. Can also use inference and omit theNSLineBreakMode
, like so:button.titleLabel?.lineBreakMode = .ByWordWrapping
.
– mjswensen
Aug 18 '15 at 22:49
|
show 3 more comments
For iOS 6 and above, use the following to allow multiple lines:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
// you probably want to center it
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if you want to
[button setTitle: @"Line1nLine2" forState: UIControlStateNormal];
For iOS 5 and below use the following to allow multiple lines:
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
// you probably want to center it
button.titleLabel.textAlignment = UITextAlignmentCenter;
[button setTitle: @"Line1nLine2" forState: UIControlStateNormal];
2017, for iOS9 forward,
generally, just do these two things:
- choose "Attributed Text"
- on the "Line Break" popup select "Word Wrap"
For iOS 6 and above, use the following to allow multiple lines:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
// you probably want to center it
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if you want to
[button setTitle: @"Line1nLine2" forState: UIControlStateNormal];
For iOS 5 and below use the following to allow multiple lines:
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
// you probably want to center it
button.titleLabel.textAlignment = UITextAlignmentCenter;
[button setTitle: @"Line1nLine2" forState: UIControlStateNormal];
2017, for iOS9 forward,
generally, just do these two things:
- choose "Attributed Text"
- on the "Line Break" popup select "Word Wrap"
edited Dec 21 '17 at 15:54
Fattie
19.8k31209455
19.8k31209455
answered Dec 1 '09 at 22:34
jessecurryjessecurry
19.4k84542
19.4k84542
5
Please note these assignments are deprecated in iOS 6. See the answer below by @NiKKi for the updated syntax.
– Aaron Brager
Jan 9 '13 at 22:36
3
Just so people know: this does not work if you're using NSAttributedString
– The dude
Oct 29 '13 at 12:08
22
Actually, just add button.titleLabel.numberOfLines = 0; That will make the lines unlimited. And button.titleLabel.textAlignment = NSTextAlignmentLeft; if you want left justified text as the title is centered by default.
– RyJ
Aug 21 '14 at 16:00
4
In swiftbutton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
– Robert
Jan 25 '15 at 17:36
1
Thanks @Robert for the swift solution. Can also use inference and omit theNSLineBreakMode
, like so:button.titleLabel?.lineBreakMode = .ByWordWrapping
.
– mjswensen
Aug 18 '15 at 22:49
|
show 3 more comments
5
Please note these assignments are deprecated in iOS 6. See the answer below by @NiKKi for the updated syntax.
– Aaron Brager
Jan 9 '13 at 22:36
3
Just so people know: this does not work if you're using NSAttributedString
– The dude
Oct 29 '13 at 12:08
22
Actually, just add button.titleLabel.numberOfLines = 0; That will make the lines unlimited. And button.titleLabel.textAlignment = NSTextAlignmentLeft; if you want left justified text as the title is centered by default.
– RyJ
Aug 21 '14 at 16:00
4
In swiftbutton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
– Robert
Jan 25 '15 at 17:36
1
Thanks @Robert for the swift solution. Can also use inference and omit theNSLineBreakMode
, like so:button.titleLabel?.lineBreakMode = .ByWordWrapping
.
– mjswensen
Aug 18 '15 at 22:49
5
5
Please note these assignments are deprecated in iOS 6. See the answer below by @NiKKi for the updated syntax.
– Aaron Brager
Jan 9 '13 at 22:36
Please note these assignments are deprecated in iOS 6. See the answer below by @NiKKi for the updated syntax.
– Aaron Brager
Jan 9 '13 at 22:36
3
3
Just so people know: this does not work if you're using NSAttributedString
– The dude
Oct 29 '13 at 12:08
Just so people know: this does not work if you're using NSAttributedString
– The dude
Oct 29 '13 at 12:08
22
22
Actually, just add button.titleLabel.numberOfLines = 0; That will make the lines unlimited. And button.titleLabel.textAlignment = NSTextAlignmentLeft; if you want left justified text as the title is centered by default.
– RyJ
Aug 21 '14 at 16:00
Actually, just add button.titleLabel.numberOfLines = 0; That will make the lines unlimited. And button.titleLabel.textAlignment = NSTextAlignmentLeft; if you want left justified text as the title is centered by default.
– RyJ
Aug 21 '14 at 16:00
4
4
In swift
button.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
– Robert
Jan 25 '15 at 17:36
In swift
button.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
– Robert
Jan 25 '15 at 17:36
1
1
Thanks @Robert for the swift solution. Can also use inference and omit the
NSLineBreakMode
, like so: button.titleLabel?.lineBreakMode = .ByWordWrapping
.– mjswensen
Aug 18 '15 at 22:49
Thanks @Robert for the swift solution. Can also use inference and omit the
NSLineBreakMode
, like so: button.titleLabel?.lineBreakMode = .ByWordWrapping
.– mjswensen
Aug 18 '15 at 22:49
|
show 3 more comments
The selected answer is correct but if you prefer to do this sort of thing in Interface Builder you can do this:
36
Thanks to my 24 year old self for writing this answer, from 28 year old self.
– Adam Waite
May 31 '18 at 22:16
3
And to stay with the Interface Builder only setup, one should settitleLabel.textAlignment
withNumber
value to1
inUser Defined Runtime Attributed
to make the text centered
– AnthoPak
Jun 14 '18 at 11:05
1
Thanks to your 28 year old self from my 24 year old self!
– Daniel Springer
Nov 22 '18 at 3:20
add a comment |
The selected answer is correct but if you prefer to do this sort of thing in Interface Builder you can do this:
36
Thanks to my 24 year old self for writing this answer, from 28 year old self.
– Adam Waite
May 31 '18 at 22:16
3
And to stay with the Interface Builder only setup, one should settitleLabel.textAlignment
withNumber
value to1
inUser Defined Runtime Attributed
to make the text centered
– AnthoPak
Jun 14 '18 at 11:05
1
Thanks to your 28 year old self from my 24 year old self!
– Daniel Springer
Nov 22 '18 at 3:20
add a comment |
The selected answer is correct but if you prefer to do this sort of thing in Interface Builder you can do this:
The selected answer is correct but if you prefer to do this sort of thing in Interface Builder you can do this:
edited Dec 3 '14 at 22:43
answered May 14 '14 at 15:36
Adam WaiteAdam Waite
14k19110138
14k19110138
36
Thanks to my 24 year old self for writing this answer, from 28 year old self.
– Adam Waite
May 31 '18 at 22:16
3
And to stay with the Interface Builder only setup, one should settitleLabel.textAlignment
withNumber
value to1
inUser Defined Runtime Attributed
to make the text centered
– AnthoPak
Jun 14 '18 at 11:05
1
Thanks to your 28 year old self from my 24 year old self!
– Daniel Springer
Nov 22 '18 at 3:20
add a comment |
36
Thanks to my 24 year old self for writing this answer, from 28 year old self.
– Adam Waite
May 31 '18 at 22:16
3
And to stay with the Interface Builder only setup, one should settitleLabel.textAlignment
withNumber
value to1
inUser Defined Runtime Attributed
to make the text centered
– AnthoPak
Jun 14 '18 at 11:05
1
Thanks to your 28 year old self from my 24 year old self!
– Daniel Springer
Nov 22 '18 at 3:20
36
36
Thanks to my 24 year old self for writing this answer, from 28 year old self.
– Adam Waite
May 31 '18 at 22:16
Thanks to my 24 year old self for writing this answer, from 28 year old self.
– Adam Waite
May 31 '18 at 22:16
3
3
And to stay with the Interface Builder only setup, one should set
titleLabel.textAlignment
with Number
value to 1
in User Defined Runtime Attributed
to make the text centered– AnthoPak
Jun 14 '18 at 11:05
And to stay with the Interface Builder only setup, one should set
titleLabel.textAlignment
with Number
value to 1
in User Defined Runtime Attributed
to make the text centered– AnthoPak
Jun 14 '18 at 11:05
1
1
Thanks to your 28 year old self from my 24 year old self!
– Daniel Springer
Nov 22 '18 at 3:20
Thanks to your 28 year old self from my 24 year old self!
– Daniel Springer
Nov 22 '18 at 3:20
add a comment |
For IOS 6 :
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
As
UILineBreakModeWordWrap and UITextAlignmentCenter
are deprecated in IOS 6 onwards..
InsideNSText.h
in theFoundation
there is no deprecated added. Its available from 6.0 but not deprecated.
– Alex Cio
May 8 '15 at 11:42
In swift:button.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel?.textAlignment = NSTextAlignment.Center
– jcity
Dec 2 '15 at 0:56
add a comment |
For IOS 6 :
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
As
UILineBreakModeWordWrap and UITextAlignmentCenter
are deprecated in IOS 6 onwards..
InsideNSText.h
in theFoundation
there is no deprecated added. Its available from 6.0 but not deprecated.
– Alex Cio
May 8 '15 at 11:42
In swift:button.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel?.textAlignment = NSTextAlignment.Center
– jcity
Dec 2 '15 at 0:56
add a comment |
For IOS 6 :
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
As
UILineBreakModeWordWrap and UITextAlignmentCenter
are deprecated in IOS 6 onwards..
For IOS 6 :
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
As
UILineBreakModeWordWrap and UITextAlignmentCenter
are deprecated in IOS 6 onwards..
answered Oct 8 '12 at 7:14
NiKKiNiKKi
2,87122337
2,87122337
InsideNSText.h
in theFoundation
there is no deprecated added. Its available from 6.0 but not deprecated.
– Alex Cio
May 8 '15 at 11:42
In swift:button.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel?.textAlignment = NSTextAlignment.Center
– jcity
Dec 2 '15 at 0:56
add a comment |
InsideNSText.h
in theFoundation
there is no deprecated added. Its available from 6.0 but not deprecated.
– Alex Cio
May 8 '15 at 11:42
In swift:button.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel?.textAlignment = NSTextAlignment.Center
– jcity
Dec 2 '15 at 0:56
Inside
NSText.h
in the Foundation
there is no deprecated added. Its available from 6.0 but not deprecated.– Alex Cio
May 8 '15 at 11:42
Inside
NSText.h
in the Foundation
there is no deprecated added. Its available from 6.0 but not deprecated.– Alex Cio
May 8 '15 at 11:42
In swift:
button.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel?.textAlignment = NSTextAlignment.Center
– jcity
Dec 2 '15 at 0:56
In swift:
button.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel?.textAlignment = NSTextAlignment.Center
– jcity
Dec 2 '15 at 0:56
add a comment |
If you want to add a button with the title centered with multiple lines, set your Interface Builder's settings for the button:
[]
Can you add a textual description of how to achieve this. An image is great, but if it becomes unavailable your answer will be useless.
– Rory McCrossan
Oct 21 '15 at 9:21
1
@RoryMcCrossan Hi, i added an image above. Can you view it? Please note, Xcode 7 is still buggy so button title might disappear. However, once you run the app you will get the desired result.
– user5440039
Oct 21 '15 at 10:03
2
This is the best answer in this thread, actually. Works immediately and shows centered text from IB. Thanks!
– RainCast
Oct 30 '16 at 23:00
@user5440039 Thanks for the great answer. There's no need to add a textual description.
– Fattie
Dec 7 '16 at 15:11
1
You made my day, thanks for pointing it out (y).
– Irfan
Apr 25 '17 at 8:03
add a comment |
If you want to add a button with the title centered with multiple lines, set your Interface Builder's settings for the button:
[]
Can you add a textual description of how to achieve this. An image is great, but if it becomes unavailable your answer will be useless.
– Rory McCrossan
Oct 21 '15 at 9:21
1
@RoryMcCrossan Hi, i added an image above. Can you view it? Please note, Xcode 7 is still buggy so button title might disappear. However, once you run the app you will get the desired result.
– user5440039
Oct 21 '15 at 10:03
2
This is the best answer in this thread, actually. Works immediately and shows centered text from IB. Thanks!
– RainCast
Oct 30 '16 at 23:00
@user5440039 Thanks for the great answer. There's no need to add a textual description.
– Fattie
Dec 7 '16 at 15:11
1
You made my day, thanks for pointing it out (y).
– Irfan
Apr 25 '17 at 8:03
add a comment |
If you want to add a button with the title centered with multiple lines, set your Interface Builder's settings for the button:
[]
If you want to add a button with the title centered with multiple lines, set your Interface Builder's settings for the button:
[]
edited Oct 24 '15 at 1:35
Jamal
61762229
61762229
answered Oct 21 '15 at 9:03
user5440039user5440039
52447
52447
Can you add a textual description of how to achieve this. An image is great, but if it becomes unavailable your answer will be useless.
– Rory McCrossan
Oct 21 '15 at 9:21
1
@RoryMcCrossan Hi, i added an image above. Can you view it? Please note, Xcode 7 is still buggy so button title might disappear. However, once you run the app you will get the desired result.
– user5440039
Oct 21 '15 at 10:03
2
This is the best answer in this thread, actually. Works immediately and shows centered text from IB. Thanks!
– RainCast
Oct 30 '16 at 23:00
@user5440039 Thanks for the great answer. There's no need to add a textual description.
– Fattie
Dec 7 '16 at 15:11
1
You made my day, thanks for pointing it out (y).
– Irfan
Apr 25 '17 at 8:03
add a comment |
Can you add a textual description of how to achieve this. An image is great, but if it becomes unavailable your answer will be useless.
– Rory McCrossan
Oct 21 '15 at 9:21
1
@RoryMcCrossan Hi, i added an image above. Can you view it? Please note, Xcode 7 is still buggy so button title might disappear. However, once you run the app you will get the desired result.
– user5440039
Oct 21 '15 at 10:03
2
This is the best answer in this thread, actually. Works immediately and shows centered text from IB. Thanks!
– RainCast
Oct 30 '16 at 23:00
@user5440039 Thanks for the great answer. There's no need to add a textual description.
– Fattie
Dec 7 '16 at 15:11
1
You made my day, thanks for pointing it out (y).
– Irfan
Apr 25 '17 at 8:03
Can you add a textual description of how to achieve this. An image is great, but if it becomes unavailable your answer will be useless.
– Rory McCrossan
Oct 21 '15 at 9:21
Can you add a textual description of how to achieve this. An image is great, but if it becomes unavailable your answer will be useless.
– Rory McCrossan
Oct 21 '15 at 9:21
1
1
@RoryMcCrossan Hi, i added an image above. Can you view it? Please note, Xcode 7 is still buggy so button title might disappear. However, once you run the app you will get the desired result.
– user5440039
Oct 21 '15 at 10:03
@RoryMcCrossan Hi, i added an image above. Can you view it? Please note, Xcode 7 is still buggy so button title might disappear. However, once you run the app you will get the desired result.
– user5440039
Oct 21 '15 at 10:03
2
2
This is the best answer in this thread, actually. Works immediately and shows centered text from IB. Thanks!
– RainCast
Oct 30 '16 at 23:00
This is the best answer in this thread, actually. Works immediately and shows centered text from IB. Thanks!
– RainCast
Oct 30 '16 at 23:00
@user5440039 Thanks for the great answer. There's no need to add a textual description.
– Fattie
Dec 7 '16 at 15:11
@user5440039 Thanks for the great answer. There's no need to add a textual description.
– Fattie
Dec 7 '16 at 15:11
1
1
You made my day, thanks for pointing it out (y).
– Irfan
Apr 25 '17 at 8:03
You made my day, thanks for pointing it out (y).
– Irfan
Apr 25 '17 at 8:03
add a comment |
To restate Roger Nolan's suggestion, but with explicit code, this is the general solution:
button.titleLabel?.numberOfLines = 0
add a comment |
To restate Roger Nolan's suggestion, but with explicit code, this is the general solution:
button.titleLabel?.numberOfLines = 0
add a comment |
To restate Roger Nolan's suggestion, but with explicit code, this is the general solution:
button.titleLabel?.numberOfLines = 0
To restate Roger Nolan's suggestion, but with explicit code, this is the general solution:
button.titleLabel?.numberOfLines = 0
edited May 12 '15 at 23:50
ma11hew28
57k94373560
57k94373560
answered Oct 28 '10 at 15:45
baudotbaudot
1,1251430
1,1251430
add a comment |
add a comment |
SWIFT 3
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.setTitle("ButtonnTitle",for: .normal)
add a comment |
SWIFT 3
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.setTitle("ButtonnTitle",for: .normal)
add a comment |
SWIFT 3
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.setTitle("ButtonnTitle",for: .normal)
SWIFT 3
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.setTitle("ButtonnTitle",for: .normal)
answered May 8 '17 at 9:56
Md. Ibrahim HassanMd. Ibrahim Hassan
3,65711332
3,65711332
add a comment |
add a comment |
Left align on iOS7 with autolayout:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentLeft;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
add a comment |
Left align on iOS7 with autolayout:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentLeft;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
add a comment |
Left align on iOS7 with autolayout:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentLeft;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
Left align on iOS7 with autolayout:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentLeft;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
answered Jun 28 '13 at 19:07
neoneyeneoneye
31.6k19134125
31.6k19134125
add a comment |
add a comment |
There is a much easier way:
someButton.lineBreakMode = UILineBreakModeWordWrap;
(Edit for iOS 3 and later:)
someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
4
UIButton.lineBreakMode was deprecated in 3.0, so that's no longer a good option.
– Christopher Pickslay
Jan 17 '11 at 23:12
1
lineBreakMode is deprecated only as a direct property of UIButton. We are directed to "Use the lineBreakMode property of the titleLabel instead." I edited Valerii's answer accordingly. It's still a good option.
– Wienke
Oct 26 '12 at 18:57
add a comment |
There is a much easier way:
someButton.lineBreakMode = UILineBreakModeWordWrap;
(Edit for iOS 3 and later:)
someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
4
UIButton.lineBreakMode was deprecated in 3.0, so that's no longer a good option.
– Christopher Pickslay
Jan 17 '11 at 23:12
1
lineBreakMode is deprecated only as a direct property of UIButton. We are directed to "Use the lineBreakMode property of the titleLabel instead." I edited Valerii's answer accordingly. It's still a good option.
– Wienke
Oct 26 '12 at 18:57
add a comment |
There is a much easier way:
someButton.lineBreakMode = UILineBreakModeWordWrap;
(Edit for iOS 3 and later:)
someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
There is a much easier way:
someButton.lineBreakMode = UILineBreakModeWordWrap;
(Edit for iOS 3 and later:)
someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
edited Oct 26 '12 at 19:05
Wienke
3,1232338
3,1232338
answered Oct 25 '09 at 19:48
Valerii HioraValerii Hiora
1,492138
1,492138
4
UIButton.lineBreakMode was deprecated in 3.0, so that's no longer a good option.
– Christopher Pickslay
Jan 17 '11 at 23:12
1
lineBreakMode is deprecated only as a direct property of UIButton. We are directed to "Use the lineBreakMode property of the titleLabel instead." I edited Valerii's answer accordingly. It's still a good option.
– Wienke
Oct 26 '12 at 18:57
add a comment |
4
UIButton.lineBreakMode was deprecated in 3.0, so that's no longer a good option.
– Christopher Pickslay
Jan 17 '11 at 23:12
1
lineBreakMode is deprecated only as a direct property of UIButton. We are directed to "Use the lineBreakMode property of the titleLabel instead." I edited Valerii's answer accordingly. It's still a good option.
– Wienke
Oct 26 '12 at 18:57
4
4
UIButton.lineBreakMode was deprecated in 3.0, so that's no longer a good option.
– Christopher Pickslay
Jan 17 '11 at 23:12
UIButton.lineBreakMode was deprecated in 3.0, so that's no longer a good option.
– Christopher Pickslay
Jan 17 '11 at 23:12
1
1
lineBreakMode is deprecated only as a direct property of UIButton. We are directed to "Use the lineBreakMode property of the titleLabel instead." I edited Valerii's answer accordingly. It's still a good option.
– Wienke
Oct 26 '12 at 18:57
lineBreakMode is deprecated only as a direct property of UIButton. We are directed to "Use the lineBreakMode property of the titleLabel instead." I edited Valerii's answer accordingly. It's still a good option.
– Wienke
Oct 26 '12 at 18:57
add a comment |
First of all, you should be aware that UIButton already has a UILabel inside it. You can set it using –setTitle:forState:
.
The problem with your example is that you need to set UILabel's numberOfLines
property to something other than its default value of 1. You should also review the lineBreakMode
property.
I'm aware of the title property, but as far as I can tell it is impossible to set it to use more than one line, hence this approach. If I disable the backgroundImage, my UILabel show up, which to me suggests a bug in either bringSubviewToFront, or UIButton itself.
– Owain Hunt
Mar 3 '09 at 11:43
add a comment |
First of all, you should be aware that UIButton already has a UILabel inside it. You can set it using –setTitle:forState:
.
The problem with your example is that you need to set UILabel's numberOfLines
property to something other than its default value of 1. You should also review the lineBreakMode
property.
I'm aware of the title property, but as far as I can tell it is impossible to set it to use more than one line, hence this approach. If I disable the backgroundImage, my UILabel show up, which to me suggests a bug in either bringSubviewToFront, or UIButton itself.
– Owain Hunt
Mar 3 '09 at 11:43
add a comment |
First of all, you should be aware that UIButton already has a UILabel inside it. You can set it using –setTitle:forState:
.
The problem with your example is that you need to set UILabel's numberOfLines
property to something other than its default value of 1. You should also review the lineBreakMode
property.
First of all, you should be aware that UIButton already has a UILabel inside it. You can set it using –setTitle:forState:
.
The problem with your example is that you need to set UILabel's numberOfLines
property to something other than its default value of 1. You should also review the lineBreakMode
property.
answered Mar 3 '09 at 8:35
RogRog
13.4k84571
13.4k84571
I'm aware of the title property, but as far as I can tell it is impossible to set it to use more than one line, hence this approach. If I disable the backgroundImage, my UILabel show up, which to me suggests a bug in either bringSubviewToFront, or UIButton itself.
– Owain Hunt
Mar 3 '09 at 11:43
add a comment |
I'm aware of the title property, but as far as I can tell it is impossible to set it to use more than one line, hence this approach. If I disable the backgroundImage, my UILabel show up, which to me suggests a bug in either bringSubviewToFront, or UIButton itself.
– Owain Hunt
Mar 3 '09 at 11:43
I'm aware of the title property, but as far as I can tell it is impossible to set it to use more than one line, hence this approach. If I disable the backgroundImage, my UILabel show up, which to me suggests a bug in either bringSubviewToFront, or UIButton itself.
– Owain Hunt
Mar 3 '09 at 11:43
I'm aware of the title property, but as far as I can tell it is impossible to set it to use more than one line, hence this approach. If I disable the backgroundImage, my UILabel show up, which to me suggests a bug in either bringSubviewToFront, or UIButton itself.
– Owain Hunt
Mar 3 '09 at 11:43
add a comment |
In Xcode 9.3 you can do it by using storyboard like below,
You need to set button title textAlignment to center
button.titleLabel?.textAlignment = .center
You don't need to set title text with new line (n) like below,
button.setTitle("GoodnAnswer",for: .normal)
Simply set title,
button.setTitle("Good Answer",for: .normal)
Here is the result,
myButton.titleLabel.textAlignment = NSTextAlignmentCenter
statement is also needed.
– tounaobun
Apr 12 at 11:53
add a comment |
In Xcode 9.3 you can do it by using storyboard like below,
You need to set button title textAlignment to center
button.titleLabel?.textAlignment = .center
You don't need to set title text with new line (n) like below,
button.setTitle("GoodnAnswer",for: .normal)
Simply set title,
button.setTitle("Good Answer",for: .normal)
Here is the result,
myButton.titleLabel.textAlignment = NSTextAlignmentCenter
statement is also needed.
– tounaobun
Apr 12 at 11:53
add a comment |
In Xcode 9.3 you can do it by using storyboard like below,
You need to set button title textAlignment to center
button.titleLabel?.textAlignment = .center
You don't need to set title text with new line (n) like below,
button.setTitle("GoodnAnswer",for: .normal)
Simply set title,
button.setTitle("Good Answer",for: .normal)
Here is the result,
In Xcode 9.3 you can do it by using storyboard like below,
You need to set button title textAlignment to center
button.titleLabel?.textAlignment = .center
You don't need to set title text with new line (n) like below,
button.setTitle("GoodnAnswer",for: .normal)
Simply set title,
button.setTitle("Good Answer",for: .normal)
Here is the result,
answered May 31 '18 at 6:14
Nazrul IslamNazrul Islam
443613
443613
myButton.titleLabel.textAlignment = NSTextAlignmentCenter
statement is also needed.
– tounaobun
Apr 12 at 11:53
add a comment |
myButton.titleLabel.textAlignment = NSTextAlignmentCenter
statement is also needed.
– tounaobun
Apr 12 at 11:53
myButton.titleLabel.textAlignment = NSTextAlignmentCenter
statement is also needed.– tounaobun
Apr 12 at 11:53
myButton.titleLabel.textAlignment = NSTextAlignmentCenter
statement is also needed.– tounaobun
Apr 12 at 11:53
add a comment |
For those who are using Xcode 4's storyboard, you can click on the button, and on the right side Utilities pane under Attributes Inspector, you'll see an option for Line Break. Choose Word Wrap, and you should be good to go.
This seems to work but it doesn't center when I tried it
– Matt Wolfe
Sep 12 '13 at 1:29
add a comment |
For those who are using Xcode 4's storyboard, you can click on the button, and on the right side Utilities pane under Attributes Inspector, you'll see an option for Line Break. Choose Word Wrap, and you should be good to go.
This seems to work but it doesn't center when I tried it
– Matt Wolfe
Sep 12 '13 at 1:29
add a comment |
For those who are using Xcode 4's storyboard, you can click on the button, and on the right side Utilities pane under Attributes Inspector, you'll see an option for Line Break. Choose Word Wrap, and you should be good to go.
For those who are using Xcode 4's storyboard, you can click on the button, and on the right side Utilities pane under Attributes Inspector, you'll see an option for Line Break. Choose Word Wrap, and you should be good to go.
answered May 9 '12 at 18:12
JackJack
2,34452638
2,34452638
This seems to work but it doesn't center when I tried it
– Matt Wolfe
Sep 12 '13 at 1:29
add a comment |
This seems to work but it doesn't center when I tried it
– Matt Wolfe
Sep 12 '13 at 1:29
This seems to work but it doesn't center when I tried it
– Matt Wolfe
Sep 12 '13 at 1:29
This seems to work but it doesn't center when I tried it
– Matt Wolfe
Sep 12 '13 at 1:29
add a comment |
Answers here tell you how to achieve multiline button title programmatically.
I just wanted to add that if you are using storyboards, you can type [Ctrl+Enter] to force a newline on a button title field.
HTH
add a comment |
Answers here tell you how to achieve multiline button title programmatically.
I just wanted to add that if you are using storyboards, you can type [Ctrl+Enter] to force a newline on a button title field.
HTH
add a comment |
Answers here tell you how to achieve multiline button title programmatically.
I just wanted to add that if you are using storyboards, you can type [Ctrl+Enter] to force a newline on a button title field.
HTH
Answers here tell you how to achieve multiline button title programmatically.
I just wanted to add that if you are using storyboards, you can type [Ctrl+Enter] to force a newline on a button title field.
HTH
answered May 1 '13 at 9:50
user2338871user2338871
591
591
add a comment |
add a comment |
As to Brent's idea of putting the title UILabel as sibling view, it doesn't seem to me like a very good idea. I keep thinking in interaction problems with the UILabel due to its touch events not getting through the UIButton's view.
On the other hand, with a UILabel as subview of the UIButton, I'm pretty confortable knowing that the touch events will always be propagated to the UILabel's superview.
I did take this approach and didn't notice any of the problems reported with backgroundImage. I added this code in the -titleRectForContentRect: of a UIButton subclass but the code can also be placed in drawing routine of the UIButton superview, which in that case you shall replace all references to self with the UIButton's variable.
#define TITLE_LABEL_TAG 1234
- (CGRect)titleRectForContentRect:(CGRect)rect
{
// define the desired title inset margins based on the whole rect and its padding
UIEdgeInsets padding = [self titleEdgeInsets];
CGRect titleRect = CGRectMake(rect.origin.x + padding.left,
rect.origin.x + padding.top,
rect.size.width - (padding.right + padding.left),
rect.size.height - (padding.bottom + padding].top));
// save the current title view appearance
NSString *title = [self currentTitle];
UIColor *titleColor = [self currentTitleColor];
UIColor *titleShadowColor = [self currentTitleShadowColor];
// we only want to add our custom label once; only 1st pass shall return nil
UILabel *titleLabel = (UILabel*)[self viewWithTag:TITLE_LABEL_TAG];
if (!titleLabel)
{
// no custom label found (1st pass), we will be creating & adding it as subview
titleLabel = [[UILabel alloc] initWithFrame:titleRect];
[titleLabel setTag:TITLE_LABEL_TAG];
// make it multi-line
[titleLabel setNumberOfLines:0];
[titleLabel setLineBreakMode:UILineBreakModeWordWrap];
// title appearance setup; be at will to modify
[titleLabel setBackgroundColor:[UIColor clearColor]];
[titleLabel setFont:[self font]];
[titleLabel setShadowOffset:CGSizeMake(0, 1)];
[titleLabel setTextAlignment:UITextAlignmentCenter];
[self addSubview:titleLabel];
[titleLabel release];
}
// finally, put our label in original title view's state
[titleLabel setText:title];
[titleLabel setTextColor:titleColor];
[titleLabel setShadowColor:titleShadowColor];
// and return empty rect so that the original title view is hidden
return CGRectZero;
}
I did take the time and wrote a bit more about this here. There, I also point a shorter solution, though it doesn't quite fit all the scenarios and involves some private views hacking. Also there, you can download an UIButton subclass ready to be used.
add a comment |
As to Brent's idea of putting the title UILabel as sibling view, it doesn't seem to me like a very good idea. I keep thinking in interaction problems with the UILabel due to its touch events not getting through the UIButton's view.
On the other hand, with a UILabel as subview of the UIButton, I'm pretty confortable knowing that the touch events will always be propagated to the UILabel's superview.
I did take this approach and didn't notice any of the problems reported with backgroundImage. I added this code in the -titleRectForContentRect: of a UIButton subclass but the code can also be placed in drawing routine of the UIButton superview, which in that case you shall replace all references to self with the UIButton's variable.
#define TITLE_LABEL_TAG 1234
- (CGRect)titleRectForContentRect:(CGRect)rect
{
// define the desired title inset margins based on the whole rect and its padding
UIEdgeInsets padding = [self titleEdgeInsets];
CGRect titleRect = CGRectMake(rect.origin.x + padding.left,
rect.origin.x + padding.top,
rect.size.width - (padding.right + padding.left),
rect.size.height - (padding.bottom + padding].top));
// save the current title view appearance
NSString *title = [self currentTitle];
UIColor *titleColor = [self currentTitleColor];
UIColor *titleShadowColor = [self currentTitleShadowColor];
// we only want to add our custom label once; only 1st pass shall return nil
UILabel *titleLabel = (UILabel*)[self viewWithTag:TITLE_LABEL_TAG];
if (!titleLabel)
{
// no custom label found (1st pass), we will be creating & adding it as subview
titleLabel = [[UILabel alloc] initWithFrame:titleRect];
[titleLabel setTag:TITLE_LABEL_TAG];
// make it multi-line
[titleLabel setNumberOfLines:0];
[titleLabel setLineBreakMode:UILineBreakModeWordWrap];
// title appearance setup; be at will to modify
[titleLabel setBackgroundColor:[UIColor clearColor]];
[titleLabel setFont:[self font]];
[titleLabel setShadowOffset:CGSizeMake(0, 1)];
[titleLabel setTextAlignment:UITextAlignmentCenter];
[self addSubview:titleLabel];
[titleLabel release];
}
// finally, put our label in original title view's state
[titleLabel setText:title];
[titleLabel setTextColor:titleColor];
[titleLabel setShadowColor:titleShadowColor];
// and return empty rect so that the original title view is hidden
return CGRectZero;
}
I did take the time and wrote a bit more about this here. There, I also point a shorter solution, though it doesn't quite fit all the scenarios and involves some private views hacking. Also there, you can download an UIButton subclass ready to be used.
add a comment |
As to Brent's idea of putting the title UILabel as sibling view, it doesn't seem to me like a very good idea. I keep thinking in interaction problems with the UILabel due to its touch events not getting through the UIButton's view.
On the other hand, with a UILabel as subview of the UIButton, I'm pretty confortable knowing that the touch events will always be propagated to the UILabel's superview.
I did take this approach and didn't notice any of the problems reported with backgroundImage. I added this code in the -titleRectForContentRect: of a UIButton subclass but the code can also be placed in drawing routine of the UIButton superview, which in that case you shall replace all references to self with the UIButton's variable.
#define TITLE_LABEL_TAG 1234
- (CGRect)titleRectForContentRect:(CGRect)rect
{
// define the desired title inset margins based on the whole rect and its padding
UIEdgeInsets padding = [self titleEdgeInsets];
CGRect titleRect = CGRectMake(rect.origin.x + padding.left,
rect.origin.x + padding.top,
rect.size.width - (padding.right + padding.left),
rect.size.height - (padding.bottom + padding].top));
// save the current title view appearance
NSString *title = [self currentTitle];
UIColor *titleColor = [self currentTitleColor];
UIColor *titleShadowColor = [self currentTitleShadowColor];
// we only want to add our custom label once; only 1st pass shall return nil
UILabel *titleLabel = (UILabel*)[self viewWithTag:TITLE_LABEL_TAG];
if (!titleLabel)
{
// no custom label found (1st pass), we will be creating & adding it as subview
titleLabel = [[UILabel alloc] initWithFrame:titleRect];
[titleLabel setTag:TITLE_LABEL_TAG];
// make it multi-line
[titleLabel setNumberOfLines:0];
[titleLabel setLineBreakMode:UILineBreakModeWordWrap];
// title appearance setup; be at will to modify
[titleLabel setBackgroundColor:[UIColor clearColor]];
[titleLabel setFont:[self font]];
[titleLabel setShadowOffset:CGSizeMake(0, 1)];
[titleLabel setTextAlignment:UITextAlignmentCenter];
[self addSubview:titleLabel];
[titleLabel release];
}
// finally, put our label in original title view's state
[titleLabel setText:title];
[titleLabel setTextColor:titleColor];
[titleLabel setShadowColor:titleShadowColor];
// and return empty rect so that the original title view is hidden
return CGRectZero;
}
I did take the time and wrote a bit more about this here. There, I also point a shorter solution, though it doesn't quite fit all the scenarios and involves some private views hacking. Also there, you can download an UIButton subclass ready to be used.
As to Brent's idea of putting the title UILabel as sibling view, it doesn't seem to me like a very good idea. I keep thinking in interaction problems with the UILabel due to its touch events not getting through the UIButton's view.
On the other hand, with a UILabel as subview of the UIButton, I'm pretty confortable knowing that the touch events will always be propagated to the UILabel's superview.
I did take this approach and didn't notice any of the problems reported with backgroundImage. I added this code in the -titleRectForContentRect: of a UIButton subclass but the code can also be placed in drawing routine of the UIButton superview, which in that case you shall replace all references to self with the UIButton's variable.
#define TITLE_LABEL_TAG 1234
- (CGRect)titleRectForContentRect:(CGRect)rect
{
// define the desired title inset margins based on the whole rect and its padding
UIEdgeInsets padding = [self titleEdgeInsets];
CGRect titleRect = CGRectMake(rect.origin.x + padding.left,
rect.origin.x + padding.top,
rect.size.width - (padding.right + padding.left),
rect.size.height - (padding.bottom + padding].top));
// save the current title view appearance
NSString *title = [self currentTitle];
UIColor *titleColor = [self currentTitleColor];
UIColor *titleShadowColor = [self currentTitleShadowColor];
// we only want to add our custom label once; only 1st pass shall return nil
UILabel *titleLabel = (UILabel*)[self viewWithTag:TITLE_LABEL_TAG];
if (!titleLabel)
{
// no custom label found (1st pass), we will be creating & adding it as subview
titleLabel = [[UILabel alloc] initWithFrame:titleRect];
[titleLabel setTag:TITLE_LABEL_TAG];
// make it multi-line
[titleLabel setNumberOfLines:0];
[titleLabel setLineBreakMode:UILineBreakModeWordWrap];
// title appearance setup; be at will to modify
[titleLabel setBackgroundColor:[UIColor clearColor]];
[titleLabel setFont:[self font]];
[titleLabel setShadowOffset:CGSizeMake(0, 1)];
[titleLabel setTextAlignment:UITextAlignmentCenter];
[self addSubview:titleLabel];
[titleLabel release];
}
// finally, put our label in original title view's state
[titleLabel setText:title];
[titleLabel setTextColor:titleColor];
[titleLabel setShadowColor:titleShadowColor];
// and return empty rect so that the original title view is hidden
return CGRectZero;
}
I did take the time and wrote a bit more about this here. There, I also point a shorter solution, though it doesn't quite fit all the scenarios and involves some private views hacking. Also there, you can download an UIButton subclass ready to be used.
answered Mar 9 '09 at 14:25
jpedrosojpedroso
59934
59934
add a comment |
add a comment |
You have to add this code:
buttonLabel.titleLabel.numberOfLines = 0;
add a comment |
You have to add this code:
buttonLabel.titleLabel.numberOfLines = 0;
add a comment |
You have to add this code:
buttonLabel.titleLabel.numberOfLines = 0;
You have to add this code:
buttonLabel.titleLabel.numberOfLines = 0;
edited Feb 21 '18 at 12:40
JimHawkins
3,07982246
3,07982246
answered Feb 21 '18 at 11:41
Pablo BlancoPablo Blanco
764
764
add a comment |
add a comment |
It works perfectly.
Add to use this with config file like Plist, you need to use CDATA to write the multilined title, like this:
<string><![CDATA[Line1
Line2]]></string>
add a comment |
It works perfectly.
Add to use this with config file like Plist, you need to use CDATA to write the multilined title, like this:
<string><![CDATA[Line1
Line2]]></string>
add a comment |
It works perfectly.
Add to use this with config file like Plist, you need to use CDATA to write the multilined title, like this:
<string><![CDATA[Line1
Line2]]></string>
It works perfectly.
Add to use this with config file like Plist, you need to use CDATA to write the multilined title, like this:
<string><![CDATA[Line1
Line2]]></string>
answered May 11 '11 at 10:04
makiko_flymakiko_fly
495
495
add a comment |
add a comment |
If you use auto-layout on iOS 6 you might also need to set the preferredMaxLayoutWidth
property:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
button.titleLabel.preferredMaxLayoutWidth = button.frame.size.width;
add a comment |
If you use auto-layout on iOS 6 you might also need to set the preferredMaxLayoutWidth
property:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
button.titleLabel.preferredMaxLayoutWidth = button.frame.size.width;
add a comment |
If you use auto-layout on iOS 6 you might also need to set the preferredMaxLayoutWidth
property:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
button.titleLabel.preferredMaxLayoutWidth = button.frame.size.width;
If you use auto-layout on iOS 6 you might also need to set the preferredMaxLayoutWidth
property:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
button.titleLabel.preferredMaxLayoutWidth = button.frame.size.width;
answered May 1 '13 at 18:45
viallyvially
1,2591417
1,2591417
add a comment |
add a comment |
Setting lineBreakMode to NSLineBreakByWordWrapping (either in IB or code) makes button label multiline, but doesn't affect button's frame.
If button has dynamic title, there is one trick: put hidden UILabel with same font and tie it's height to button's height with layout; when set text to button and label and autolayout will make all the work.
Note
Intrinsic size height of one-line button is bigger than label's, so to prevent label's height shrink it's vertical Content Hugging Priority must be greater than button's vertical Content Compression Resistance.
add a comment |
Setting lineBreakMode to NSLineBreakByWordWrapping (either in IB or code) makes button label multiline, but doesn't affect button's frame.
If button has dynamic title, there is one trick: put hidden UILabel with same font and tie it's height to button's height with layout; when set text to button and label and autolayout will make all the work.
Note
Intrinsic size height of one-line button is bigger than label's, so to prevent label's height shrink it's vertical Content Hugging Priority must be greater than button's vertical Content Compression Resistance.
add a comment |
Setting lineBreakMode to NSLineBreakByWordWrapping (either in IB or code) makes button label multiline, but doesn't affect button's frame.
If button has dynamic title, there is one trick: put hidden UILabel with same font and tie it's height to button's height with layout; when set text to button and label and autolayout will make all the work.
Note
Intrinsic size height of one-line button is bigger than label's, so to prevent label's height shrink it's vertical Content Hugging Priority must be greater than button's vertical Content Compression Resistance.
Setting lineBreakMode to NSLineBreakByWordWrapping (either in IB or code) makes button label multiline, but doesn't affect button's frame.
If button has dynamic title, there is one trick: put hidden UILabel with same font and tie it's height to button's height with layout; when set text to button and label and autolayout will make all the work.
Note
Intrinsic size height of one-line button is bigger than label's, so to prevent label's height shrink it's vertical Content Hugging Priority must be greater than button's vertical Content Compression Resistance.
edited Sep 1 '15 at 14:56
answered Aug 31 '15 at 20:21
VarrryVarrry
1,3961517
1,3961517
add a comment |
add a comment |
If you use auto-layout.
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.numberOfLines = 2
add a comment |
If you use auto-layout.
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.numberOfLines = 2
add a comment |
If you use auto-layout.
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.numberOfLines = 2
If you use auto-layout.
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.numberOfLines = 2
edited Apr 14 '17 at 6:50
answered Dec 9 '16 at 10:55
Sourabh SharmaSourabh Sharma
5,65135168
5,65135168
add a comment |
add a comment |
These days, if you really need this sort of thing to be accessible in interface builder on a case-by-case basis, you can do it with a simple extension like this:
extension UIButton {
@IBInspectable var numberOfLines: Int {
get { return titleLabel?.numberOfLines ?? 1 }
set { titleLabel?.numberOfLines = newValue }
}
}
Then you can simply set numberOfLines as an attribute on any UIButton or UIButton subclass as if it were a label. The same goes for a whole host of other usually-inaccessible values, such as the corner radius of a view's layer, or the attributes of the shadow that it casts.
add a comment |
These days, if you really need this sort of thing to be accessible in interface builder on a case-by-case basis, you can do it with a simple extension like this:
extension UIButton {
@IBInspectable var numberOfLines: Int {
get { return titleLabel?.numberOfLines ?? 1 }
set { titleLabel?.numberOfLines = newValue }
}
}
Then you can simply set numberOfLines as an attribute on any UIButton or UIButton subclass as if it were a label. The same goes for a whole host of other usually-inaccessible values, such as the corner radius of a view's layer, or the attributes of the shadow that it casts.
add a comment |
These days, if you really need this sort of thing to be accessible in interface builder on a case-by-case basis, you can do it with a simple extension like this:
extension UIButton {
@IBInspectable var numberOfLines: Int {
get { return titleLabel?.numberOfLines ?? 1 }
set { titleLabel?.numberOfLines = newValue }
}
}
Then you can simply set numberOfLines as an attribute on any UIButton or UIButton subclass as if it were a label. The same goes for a whole host of other usually-inaccessible values, such as the corner radius of a view's layer, or the attributes of the shadow that it casts.
These days, if you really need this sort of thing to be accessible in interface builder on a case-by-case basis, you can do it with a simple extension like this:
extension UIButton {
@IBInspectable var numberOfLines: Int {
get { return titleLabel?.numberOfLines ?? 1 }
set { titleLabel?.numberOfLines = newValue }
}
}
Then you can simply set numberOfLines as an attribute on any UIButton or UIButton subclass as if it were a label. The same goes for a whole host of other usually-inaccessible values, such as the corner radius of a view's layer, or the attributes of the shadow that it casts.
answered Nov 17 '18 at 7:12
AshAsh
7,03623845
7,03623845
add a comment |
add a comment |
Roll your own button class. It's by far the best solution in the long run. UIButton and other UIKit classes are very restrictive in how you can customize them.
add a comment |
Roll your own button class. It's by far the best solution in the long run. UIButton and other UIKit classes are very restrictive in how you can customize them.
add a comment |
Roll your own button class. It's by far the best solution in the long run. UIButton and other UIKit classes are very restrictive in how you can customize them.
Roll your own button class. It's by far the best solution in the long run. UIButton and other UIKit classes are very restrictive in how you can customize them.
answered Mar 10 '09 at 13:16
unwesen
add a comment |
add a comment |
self.btnError.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
self.btnError.titleLabel?.textAlignment = .center
self.btnError.setTitle("Title", for: .normal)
add a comment |
self.btnError.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
self.btnError.titleLabel?.textAlignment = .center
self.btnError.setTitle("Title", for: .normal)
add a comment |
self.btnError.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
self.btnError.titleLabel?.textAlignment = .center
self.btnError.setTitle("Title", for: .normal)
self.btnError.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
self.btnError.titleLabel?.textAlignment = .center
self.btnError.setTitle("Title", for: .normal)
edited Aug 3 '17 at 9:47
Bugs
4,16092637
4,16092637
answered Aug 3 '17 at 9:40
Urvish ModiUrvish Modi
868710
868710
add a comment |
add a comment |
swift 4.0
btn.titleLabel?.lineBreakMode = .byWordWrapping
btn.titleLabel?.textAlignment = .center
btn.setTitle( "Line1nLine2", for: .normal)
add a comment |
swift 4.0
btn.titleLabel?.lineBreakMode = .byWordWrapping
btn.titleLabel?.textAlignment = .center
btn.setTitle( "Line1nLine2", for: .normal)
add a comment |
swift 4.0
btn.titleLabel?.lineBreakMode = .byWordWrapping
btn.titleLabel?.textAlignment = .center
btn.setTitle( "Line1nLine2", for: .normal)
swift 4.0
btn.titleLabel?.lineBreakMode = .byWordWrapping
btn.titleLabel?.textAlignment = .center
btn.setTitle( "Line1nLine2", for: .normal)
answered Mar 25 '18 at 12:50
ingcontiingconti
6,22613427
6,22613427
add a comment |
add a comment |
I incorporated jessecurry's answer within STAButton which is part of my STAControls open source library. I currently use it within one of the apps I am developing and it works for my needs. Feel free to open issues on how to improve it or send me pull requests.
add a comment |
I incorporated jessecurry's answer within STAButton which is part of my STAControls open source library. I currently use it within one of the apps I am developing and it works for my needs. Feel free to open issues on how to improve it or send me pull requests.
add a comment |
I incorporated jessecurry's answer within STAButton which is part of my STAControls open source library. I currently use it within one of the apps I am developing and it works for my needs. Feel free to open issues on how to improve it or send me pull requests.
I incorporated jessecurry's answer within STAButton which is part of my STAControls open source library. I currently use it within one of the apps I am developing and it works for my needs. Feel free to open issues on how to improve it or send me pull requests.
answered May 5 '18 at 23:27
StunnerStunner
8,0191069127
8,0191069127
add a comment |
add a comment |
I had an issue with auto-layout, after enabling multi-line the result was like this:
so the titleLabel
size doesn't affect the button size
I've added Constraints
based on contentEdgeInsets
(in this case contentEdgeInsets was (10, 10, 10, 10)
after calling makeMultiLineSupport()
:
hope it help you (swift 5.0):
extension UIButton {
func makeMultiLineSupport() {
guard let titleLabel = titleLabel else {
return
}
titleLabel.numberOfLines = 0
titleLabel.setContentHuggingPriority(.required, for: .vertical)
titleLabel.setContentHuggingPriority(.required, for: .horizontal)
addConstraints([
.init(item: titleLabel,
attribute: .top,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .top,
multiplier: 1.0,
constant: contentEdgeInsets.top),
.init(item: titleLabel,
attribute: .bottom,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .bottom,
multiplier: 1.0,
constant: contentEdgeInsets.bottom),
.init(item: titleLabel,
attribute: .left,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .left,
multiplier: 1.0,
constant: contentEdgeInsets.left),
.init(item: titleLabel,
attribute: .right,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .right,
multiplier: 1.0,
constant: contentEdgeInsets.right)
])
}
}
add a comment |
I had an issue with auto-layout, after enabling multi-line the result was like this:
so the titleLabel
size doesn't affect the button size
I've added Constraints
based on contentEdgeInsets
(in this case contentEdgeInsets was (10, 10, 10, 10)
after calling makeMultiLineSupport()
:
hope it help you (swift 5.0):
extension UIButton {
func makeMultiLineSupport() {
guard let titleLabel = titleLabel else {
return
}
titleLabel.numberOfLines = 0
titleLabel.setContentHuggingPriority(.required, for: .vertical)
titleLabel.setContentHuggingPriority(.required, for: .horizontal)
addConstraints([
.init(item: titleLabel,
attribute: .top,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .top,
multiplier: 1.0,
constant: contentEdgeInsets.top),
.init(item: titleLabel,
attribute: .bottom,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .bottom,
multiplier: 1.0,
constant: contentEdgeInsets.bottom),
.init(item: titleLabel,
attribute: .left,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .left,
multiplier: 1.0,
constant: contentEdgeInsets.left),
.init(item: titleLabel,
attribute: .right,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .right,
multiplier: 1.0,
constant: contentEdgeInsets.right)
])
}
}
add a comment |
I had an issue with auto-layout, after enabling multi-line the result was like this:
so the titleLabel
size doesn't affect the button size
I've added Constraints
based on contentEdgeInsets
(in this case contentEdgeInsets was (10, 10, 10, 10)
after calling makeMultiLineSupport()
:
hope it help you (swift 5.0):
extension UIButton {
func makeMultiLineSupport() {
guard let titleLabel = titleLabel else {
return
}
titleLabel.numberOfLines = 0
titleLabel.setContentHuggingPriority(.required, for: .vertical)
titleLabel.setContentHuggingPriority(.required, for: .horizontal)
addConstraints([
.init(item: titleLabel,
attribute: .top,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .top,
multiplier: 1.0,
constant: contentEdgeInsets.top),
.init(item: titleLabel,
attribute: .bottom,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .bottom,
multiplier: 1.0,
constant: contentEdgeInsets.bottom),
.init(item: titleLabel,
attribute: .left,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .left,
multiplier: 1.0,
constant: contentEdgeInsets.left),
.init(item: titleLabel,
attribute: .right,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .right,
multiplier: 1.0,
constant: contentEdgeInsets.right)
])
}
}
I had an issue with auto-layout, after enabling multi-line the result was like this:
so the titleLabel
size doesn't affect the button size
I've added Constraints
based on contentEdgeInsets
(in this case contentEdgeInsets was (10, 10, 10, 10)
after calling makeMultiLineSupport()
:
hope it help you (swift 5.0):
extension UIButton {
func makeMultiLineSupport() {
guard let titleLabel = titleLabel else {
return
}
titleLabel.numberOfLines = 0
titleLabel.setContentHuggingPriority(.required, for: .vertical)
titleLabel.setContentHuggingPriority(.required, for: .horizontal)
addConstraints([
.init(item: titleLabel,
attribute: .top,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .top,
multiplier: 1.0,
constant: contentEdgeInsets.top),
.init(item: titleLabel,
attribute: .bottom,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .bottom,
multiplier: 1.0,
constant: contentEdgeInsets.bottom),
.init(item: titleLabel,
attribute: .left,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .left,
multiplier: 1.0,
constant: contentEdgeInsets.left),
.init(item: titleLabel,
attribute: .right,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .right,
multiplier: 1.0,
constant: contentEdgeInsets.right)
])
}
}
answered Apr 11 at 21:25
Amir KhorsandiAmir Khorsandi
1,10111122
1,10111122
add a comment |
add a comment |
Although it's okay to add a subview to a control, there's no guarantee it'll actually work, because the control might not expect it to be there and might thus behave poorly. If you can get away with it, just add the label as a sibling view of the button and set its frame so that it overlaps the button; as long as it's set to appear on top of the button, nothing the button can do will obscure it.
In other words:
[button.superview addSubview:myLabel];
myLabel.center = button.center;
2
Please, if you suggest this kind of ugly approach at least don't make mistakes in your code example :). The label shouldn't have the same center as button if it's a subview. Use myLabel.frame = button.bounds; or myLabel.center = cgPointMake(button.frame.size.with*0.5,button.frame.size.height*0.5)
– JakubKnejzlik
Aug 6 '14 at 14:53
1
@GrizzlyNetch I'm specifically advising not to add it as a subview of the button.addSubview:
here adds it tobutton
's superview, thus making it a sibling of the button, so matching their centers is correct.
– Brent Royal-Gordon
Aug 8 '14 at 6:49
Ah, my mistake! You are right, I've missed the "small" fact it's in the superview :D ... sorry :)
– JakubKnejzlik
Aug 8 '14 at 8:16
add a comment |
Although it's okay to add a subview to a control, there's no guarantee it'll actually work, because the control might not expect it to be there and might thus behave poorly. If you can get away with it, just add the label as a sibling view of the button and set its frame so that it overlaps the button; as long as it's set to appear on top of the button, nothing the button can do will obscure it.
In other words:
[button.superview addSubview:myLabel];
myLabel.center = button.center;
2
Please, if you suggest this kind of ugly approach at least don't make mistakes in your code example :). The label shouldn't have the same center as button if it's a subview. Use myLabel.frame = button.bounds; or myLabel.center = cgPointMake(button.frame.size.with*0.5,button.frame.size.height*0.5)
– JakubKnejzlik
Aug 6 '14 at 14:53
1
@GrizzlyNetch I'm specifically advising not to add it as a subview of the button.addSubview:
here adds it tobutton
's superview, thus making it a sibling of the button, so matching their centers is correct.
– Brent Royal-Gordon
Aug 8 '14 at 6:49
Ah, my mistake! You are right, I've missed the "small" fact it's in the superview :D ... sorry :)
– JakubKnejzlik
Aug 8 '14 at 8:16
add a comment |
Although it's okay to add a subview to a control, there's no guarantee it'll actually work, because the control might not expect it to be there and might thus behave poorly. If you can get away with it, just add the label as a sibling view of the button and set its frame so that it overlaps the button; as long as it's set to appear on top of the button, nothing the button can do will obscure it.
In other words:
[button.superview addSubview:myLabel];
myLabel.center = button.center;
Although it's okay to add a subview to a control, there's no guarantee it'll actually work, because the control might not expect it to be there and might thus behave poorly. If you can get away with it, just add the label as a sibling view of the button and set its frame so that it overlaps the button; as long as it's set to appear on top of the button, nothing the button can do will obscure it.
In other words:
[button.superview addSubview:myLabel];
myLabel.center = button.center;
answered Mar 3 '09 at 12:04
Brent Royal-GordonBrent Royal-Gordon
13.5k54781
13.5k54781
2
Please, if you suggest this kind of ugly approach at least don't make mistakes in your code example :). The label shouldn't have the same center as button if it's a subview. Use myLabel.frame = button.bounds; or myLabel.center = cgPointMake(button.frame.size.with*0.5,button.frame.size.height*0.5)
– JakubKnejzlik
Aug 6 '14 at 14:53
1
@GrizzlyNetch I'm specifically advising not to add it as a subview of the button.addSubview:
here adds it tobutton
's superview, thus making it a sibling of the button, so matching their centers is correct.
– Brent Royal-Gordon
Aug 8 '14 at 6:49
Ah, my mistake! You are right, I've missed the "small" fact it's in the superview :D ... sorry :)
– JakubKnejzlik
Aug 8 '14 at 8:16
add a comment |
2
Please, if you suggest this kind of ugly approach at least don't make mistakes in your code example :). The label shouldn't have the same center as button if it's a subview. Use myLabel.frame = button.bounds; or myLabel.center = cgPointMake(button.frame.size.with*0.5,button.frame.size.height*0.5)
– JakubKnejzlik
Aug 6 '14 at 14:53
1
@GrizzlyNetch I'm specifically advising not to add it as a subview of the button.addSubview:
here adds it tobutton
's superview, thus making it a sibling of the button, so matching their centers is correct.
– Brent Royal-Gordon
Aug 8 '14 at 6:49
Ah, my mistake! You are right, I've missed the "small" fact it's in the superview :D ... sorry :)
– JakubKnejzlik
Aug 8 '14 at 8:16
2
2
Please, if you suggest this kind of ugly approach at least don't make mistakes in your code example :). The label shouldn't have the same center as button if it's a subview. Use myLabel.frame = button.bounds; or myLabel.center = cgPointMake(button.frame.size.with*0.5,button.frame.size.height*0.5)
– JakubKnejzlik
Aug 6 '14 at 14:53
Please, if you suggest this kind of ugly approach at least don't make mistakes in your code example :). The label shouldn't have the same center as button if it's a subview. Use myLabel.frame = button.bounds; or myLabel.center = cgPointMake(button.frame.size.with*0.5,button.frame.size.height*0.5)
– JakubKnejzlik
Aug 6 '14 at 14:53
1
1
@GrizzlyNetch I'm specifically advising not to add it as a subview of the button.
addSubview:
here adds it to button
's superview, thus making it a sibling of the button, so matching their centers is correct.– Brent Royal-Gordon
Aug 8 '14 at 6:49
@GrizzlyNetch I'm specifically advising not to add it as a subview of the button.
addSubview:
here adds it to button
's superview, thus making it a sibling of the button, so matching their centers is correct.– Brent Royal-Gordon
Aug 8 '14 at 6:49
Ah, my mistake! You are right, I've missed the "small" fact it's in the superview :D ... sorry :)
– JakubKnejzlik
Aug 8 '14 at 8:16
Ah, my mistake! You are right, I've missed the "small" fact it's in the superview :D ... sorry :)
– JakubKnejzlik
Aug 8 '14 at 8:16
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f604632%2fhow-do-you-add-multi-line-text-to-a-uibutton%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
4
button.titleLabel?.numberOfLines = 0
– ma11hew28
May 12 '15 at 23:46
2
Note for this very very old QA, in modern Xcode VERY SIMPLY, CHOOSE "ATTRIBUTED TEXT" and then it's trivial, select "character wrap".
– Fattie
Dec 7 '16 at 15:05
Also see updated answer to a similar question.
– ToolmakerSteve
Mar 6 '17 at 0:11