line text to a UIButton?
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?
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:
The selected answer is correct but if you prefer to do this sort of thing in Interface Builder you can do this:
For IOS 6 :
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
As
UILineBreakModeWordWrap and UITextAlignmentCenter
are deprecated in IOS 6 onwards..
链接地址: http://www.djcxy.com/p/4832.html上一篇: 如何为UILabel添加换行符?
下一篇: 行文本到UIButton?