如何为UILabel添加换行符? [英] How to add line break for UILabel?

查看:99
本文介绍了如何为UILabel添加换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我看到我的字符串如下所示:

Let see that I have a string look like this:

NSString *longStr = @"AAAAA\nBBBBB\nCCCCC";  

如何让UILabel显示这样的信息

How do I make it so that the UILabel display the message like this


AAAAA

BBBBB

CCCCC

AAAAA
BBBBB
CCCCC

我不认为 \ n 被UILabel认可,所以我可以把任何东西都放在NSString里面,以便UILabel知道它有在那里创建换行符?

I don't think \n is recognized by UILabel, so is there anything that I can put inside NSString so that UILabel knows that it has to create a line break there?

推荐答案

使用 \ n as你在你的字符串中使用。

Use \n as you are using in your string.

将numberOfLines设置为0以允许任意数量的行。

Set numberOfLines to 0 to allow for any number of lines.

label.numberOfLines = 0;

使用 sizeWithFont:。如果你不这样做,你的文字将垂直居中或切断。

Update the label frame to match the size of the text using sizeWithFont:. If you don't do this your text will be vertically centered or cut off.

UILabel *label; // set frame to largest size you want
...
CGSize labelSize = [label.text sizeWithFont:label.font
                          constrainedToSize:label.frame.size
                              lineBreakMode:label.lineBreakMode];
label.frame = CGRectMake(
    label.frame.origin.x, label.frame.origin.y, 
    label.frame.size.width, labelSize.height);

更新:已弃用的替代

sizeWithFont:constrainedToSize :lineBreakMode:

参考,已弃用的替换sizeWithFont:在iOS 7中?

CGSize labelSize = [label.text sizeWithAttributes:@{NSFontAttributeName:label.font}];

label.frame = CGRectMake(
    label.frame.origin.x, label.frame.origin.y, 
    label.frame.size.width, labelSize.height);

这篇关于如何为UILabel添加换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆