最近开发遇到这样的需求,让label显示一行半 (其实是: 当文字内容小于一行半的时候会根据全部显示,当文字内容多余一行半的时候就显示一行半,后面拼接...),如图效果
上代码: 一共有三个方法,包含控制行间距的代码
- (void)viewDidLoad {
[super viewDidLoad];
NSString *newStr =@"天外飞鸿剧评:好剧 天外飞鸿剧评:好剧天外飞鸿剧评:好剧 天外飞鸿剧评:好剧天外飞鸿剧评:好剧 天外飞鸿剧评:好剧天外飞鸿剧评:好剧 天外飞鸿剧评:好剧天外飞鸿剧评:好剧 天外飞鸿剧评:好剧天外飞鸿剧评:好剧 天外飞鸿剧评:好剧天外飞鸿剧评:好剧 天外飞鸿剧评:好剧天外飞鸿剧评:好剧 天外飞鸿剧评:好剧";
[newStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符
newStr = [newStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
newStr = [newStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//创建label,WIDTH是宏定义的屏幕宽度
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, WIDTH-40, 100)];
label.numberOfLines = 0;
label.backgroundColor = [UIColor orangeColor];
label.textColor = [UIColor redColor];
label.font = [UIFont systemFontOfSize:14.0];
label.text = newStr;
[self.view addSubview:label];
[label sizeToFit];
NSString *string = [self getWidthWithLabel:label];
label.text = string;
[self adjustLabelLineSpacing:label];
}
//核心代码控制显示一行半的方法
- (NSString *)getWidthWithLabel:(UILabel *)label{
NSString *temp =nil;
NSString *temp1=label.text;
CGFloat length = 0;
for(int i =0; i < [label.text length]; i++)
{
temp = [label.text substringWithRange:NSMakeRange(i,1)];
// 计算宽度
CGSize size = [temp boundingRectWithSize:CGSizeMake(MAXFLOAT, 0.0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : label.font} context:nil].size;
length=length+size.width;
// 3*label.frame.size.width 此处是三行半,根据需求设置
if (length >= (3*label.frame.size.width + 0.5 * label.frame.size.width)) {
temp1= [[label.text substringToIndex:i] stringByAppendingString:@" ..."];
return temp1;
}
}
return temp1;
}
//控制行间距
-(CGSize)adjustLabelLineSpacing:(UILabel *)label
{
CGSize size = CGSizeZero;
label.text = ((NSNull *)label.text == [NSNull null] || label.text == nil) ? @"" : label.text;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:label.text];;
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
[paragraphStyle setLineSpacing:6];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, label.text.length)];
label.attributedText = attributedString;
//调节高度
size = CGSizeMake(label.frame.size.width, 500000);
CGSize labelSize = [label sizeThatFits:size];
CGRect rect = label.frame;
rect.size.width = labelSize.width;
rect.size.height = labelSize.height;
label.frame = rect;
return size;
}