首页 > iOS中UILabel中显示一个日期,日期不能自动换行

iOS中UILabel中显示一个日期,日期不能自动换行

日期能不能截断换行


有2种情况,
1如果你是用约束, 你约束x,y,宽,三个约束。和设置属性label.numberOfLines = 0。则可以自动换行

2如果你是用frame的话 要设置好足够的高度。和属性label.numberOfLines = 0。则可以自动换行


当你把 UILabel 的 numberOfLines 设置为0,并且 UIlabel 的高度够大时,就会自动换行显示


不同于其他文本,因为日期的最长长度是固定的,我建议最好缩小字体,让日期能显示完整。否则你还要去考虑下面其他控件的布局问题。


可以。需要你设置 UILabel 的 numberOfLines 属性为 0,UILabel 就会设置的 Frame 范围里自动换行显示文字。

label.numberOfLines = 0;

编辑

如果要在一行显示,使用 NSMutableAttributedString 来做字符串拼接,可以为一个字符串中的不同字符设置不同的样式,基于此,你可以把后面的日期的字体设置小一点,以便能一行显示不换行。

代码大致如下:

NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithString:@""];

NSMutableAttributedString *descriptionString = [[NSMutableAttributedString alloc] initWithString:@"截止到"];
[descriptionString addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:20]} range:NSMakeRange(0, descriptionString.length)];
[resultString appendAttributedString:descriptionString];

NSMutableAttributedString *dateString = [[NSMutableAttributedString alloc] initWithString:@"2016-01-01"];
[dateString addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:10]} range:NSMakeRange(0, dateString.length)];
[resultString appendAttributedString:dateString];

UILabel *label = [[UILabel alloc] init];
label.attributedText = resultString;

  1. 设置行数为0或者2

  2. 设置字体缩放比例均可


label.numberOfLines=0;然后宽固定。
通过方法 size = [Label.text sizeWithFont:Label.font constrainedToSize:CGSizeMake(Label.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];算出高Label的size

然后
CGRect newFrame = _nameLabel.frame;

newFrame.size.width = nameSize.width;
_nameLabel.frame = newFrame;
这就是文本自适应,就可以解决了
【热门文章】
【热门文章】