因为要计算label的动态高度问题,还要调整间距布局其他视图的时候就需要获取label自适应后的高度。获取服务器返回的字符串之后,先计算动态高度,然后借助NSMutableParagraphStyle 设置行间距,之后设置sizeTofit,这时label的frame已经发生了变化。其他子视图的布局依托label即可
NSString *textStr = @"哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈阿嘎如果哈哈人噶换人了噶尔哈哈个问哈儿哈儿哈儿ahgaerhrtharha阿嘎热噶尔尕热噶尔尕尔尕尔尕尔尕热噶热噶尔尕尔尕热噶热噶热感热个人爱人噶热供热噶二个人噶尔尕尔尕热噶尔尕尔尕二个如果热个人噶尔感染而安然噶尔尕尔尕尔尕尔尕尔尕尔阿尔噶尔阿尔高而黑人头哈突然爱人噶尔刚和人噶尔尕尔尕尔尕尔尕尔尕尔高二garga argaregareg 爱人噶尔尕热噶热狗然而噶热噶尔尕尔尕尔尕尔尕尔gearGVareGV阿尔噶尔噶尔安仁干热个人噶尔尕尔尕尔尕尔尕尔个人噶尔供热互通和侮辱他还让他啊哈让她换个人生太伤身体如何深入体会收人头和认同和深入体会收人头和深入体会是如何深入体会让他很认同和srthsrthshsrthsrht6jsrrth身体和深入体会收人头和收入好身体如何深入体会收人头和网上贴好身体如何深入体会收人头和虽然他还让他";
UIFont *textFont = [UIFont systemFontOfSize:14];
CGSize textSize = [self stringSizeWithFont:textFont string:textStr width:(KScreenW -40)];
NSLog(@"%@",NSStringFromCGSize(textSize));
UILabel *openMicPrivilegeTipsLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, textSize.width, textSize.height)];
openMicPrivilegeTipsLabel.textColor = [UIColor redColor];
openMicPrivilegeTipsLabel.text = textStr;
openMicPrivilegeTipsLabel.backgroundColor = [UIColor clearColor];
openMicPrivilegeTipsLabel.textAlignment = NSTextAlignmentLeft;
openMicPrivilegeTipsLabel.font = [UIFont systemFontOfSize:14];
openMicPrivilegeTipsLabel.numberOfLines = 0;
openMicPrivilegeTipsLabel.backgroundColor =[UIColor blueColor];
// 调整行间距
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:textStr];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:6];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [textStr length])];
openMicPrivilegeTipsLabel.attributedText = attributedString;
[self.view addSubview:openMicPrivilegeTipsLabel];
[openMicPrivilegeTipsLabel sizeToFit];
NSLog(@"%@",NSStringFromCGSize(openMicPrivilegeTipsLabel.frame.size));
}
-(CGSize)stringSizeWithFont:(UIFont *)font string:(NSString *)string width:(CGFloat)width
{
CGRect rect =[string boundingRectWithSize:CGSizeMake(width, 10000) options: NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
return rect.size;
}
- (NSMutableArray *)array {
if(_array == nil) {
_array = [[NSMutableArray alloc] init];
}
return _array;
}