Multiple lines of text in UILabel

2019-01-01 16:57发布

Is there a way to have multiple lines of text in UILabel like in the UITextView or should I use the second one instead?

25条回答
旧人旧事旧时光
2楼-- · 2019-01-01 17:27

Already answered, but you can do it manually in the storyboard too. Under Attributes Inspector for the Label, you can change Line Breaks to Word Wrap (or character wrap).

查看更多
ら面具成の殇う
3楼-- · 2019-01-01 17:28
myUILabel.numberOfLines = 0;
myUILabel.text = @"your long string here";
[myUILabel sizeToFit];
查看更多
弹指情弦暗扣
4楼-- · 2019-01-01 17:32
UILabel *helpLabel = [[UILabel alloc] init];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:label];
helpLabel.attributedText = attrString;
// helpLabel.text = label;

helpLabel.textAlignment = NSTextAlignmentCenter;
helpLabel.lineBreakMode = NSLineBreakByWordWrapping;
helpLabel.numberOfLines = 0;

For some reasons its not working for me in iOS 6 not sure why. Tried it with and without attributed text. Any suggestions.

查看更多
与君花间醉酒
5楼-- · 2019-01-01 17:33

The best solution I have found (to an otherwise frustrating problem that should have been solved in the framework) is similar to vaychick's.

Just set number of lines to 0 in either IB or code

myLabel.numberOfLines = 0;

This will display the lines needed but will reposition the label so its centered horizontally (so that a 1 line and 3 line label are aligned in their horizontal position). To fix that add:

CGRect currentFrame = myLabel.frame;
CGSize max = CGSizeMake(myLabel.frame.size.width, 500);
CGSize expected = [myString sizeWithFont:myLabel.font constrainedToSize:max lineBreakMode:myLabel.lineBreakMode]; 
currentFrame.size.height = expected.height;
myLabel.frame = currentFrame;
查看更多
栀子花@的思念
6楼-- · 2019-01-01 17:34

In IB, set number of lines to 0 (allows unlimited lines)

When typing within the text field using IB, use "alt-return" to insert a return and go to the next line (or you can copy in text already separated out by lines).

查看更多
旧时光的记忆
7楼-- · 2019-01-01 17:34

Use this to have multiple lines of text in UILabel:

textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;

Swift:

textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 0
查看更多
登录 后发表回答