ios - 如何为 UILabel 添加换行符?

标签 ios iphone uilabel newline line-breaks

让我看看我有一个像这样的字符串:

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

如何让 UILabel 显示这样的消息

AAAAA
BBBBB
CCCCC

我认为 \n 不会被 UILabel 识别,所以我可以在 NSString 中放入任何东西,以便 UILabel 知道它必须在那里创建一个换行符吗?

最佳答案

按照您在字符串中使用的方式使用 \n

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

label.numberOfLines = 0;

使用 sizeWithFont: 更新标签框架以匹配文本的大小。如果您不这样做,您的文本将垂直居中或被截断。

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:

引用,Replacement for deprecated sizeWithFont: in 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);

关于ios - 如何为 UILabel 添加换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2312899/

相关文章:

iphone - UILabel文本偏移/缩进

iphone - UITableViewCell一遍又一遍地重复

ios - 在组合中将给定的发布者失败类型设置为从不

ios - 嵌套表格和 Collection View 的 self 调整单元格

ios - Xcode 9 自定义字体不起作用

android - 添加到手机主屏幕

ios - 为什么 UIAElement 的 child 不等于自己?

iphone - 应用程序在发送和接收特殊字符时崩溃

iphone - ERROR : You are not the current participant. 当我是当前参与者时。什么?

iphone - UILabel sizeToFit - 调整下方对象的位置