让我们看看我有一个这样的字符串:
NSString *longStr = @"AAAAA\nBBBBB\nCCCCC";
如何使UILabel像这样显示消息
五星级 BBBBB CCCCC
我不认为\n能被UILabel识别,我能在NSString中放入什么东西让UILabel知道它必须在那里创建换行符吗?
让我们看看我有一个这样的字符串:
NSString *longStr = @"AAAAA\nBBBBB\nCCCCC";
如何使UILabel像这样显示消息
五星级 BBBBB CCCCC
我不认为\n能被UILabel识别,我能在NSString中放入什么东西让UILabel知道它必须在那里创建换行符吗?
当前回答
//不要忘记将numberolines设置为0
UILabel* locationTitle = [[UILabel alloc] initWithFrame:CGRectMake(5, 30, 230, 40)];
locationTitle.font = [UIFont systemFontOfSize:13.0];
locationTitle.numberOfLines = 0;
locationTitle.text = [NSString stringWithFormat:@"Eaton industries pvt. Ltd \nUK Apr 12"];
[cell addSubview:locationTitle];
其他回答
NSCharacterSet *charSet = NSCharacterSet.newlineCharacterSet;
NSString *formatted = [[unformatted componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:@"\n"];
对于任何其他人,可能有问题sizeWithFont:constrainedToSize:lineBreakMode:或任何人切换到ios8(该方法已弃用ios7),我通过使用sizeToFit来调整我的高度。
UILabel *label;
label.numberOfLines = 0;
// Setup label with desired settings
...
[label sizeToFit];
label.frame = CGRectMake(label.frame.origin.x, // Or use any desired origin
label.frame.origin.y,
label.frame.size.width, // Or use any desired width
label.frame.size.height);
在Xcode 6上,我可以在swift编程上使用\n没有问题
如果你将可用属性从普通设置为有属性…UILabel将保存多行文本,无论你的UILabel高度和宽度设置为适合你想要显示文本的屏幕区域。
对我来说,改变标签帧大小似乎是错误的,尤其是在使用自动布局时。使用appendFormat方法似乎更合适。以下是我的例子:
NSMutableString *list = [[NSMutableString alloc] init];
NSArray *textArray = @[@"AAAA", @"BBBB"];
for (NSString *string in textArray) {
[list appendFormat:@"%@\n", string.mutableCopy];
}
self.label.text = list;
self.label.numberOfLines = 0;