UILabel *label = [[UILabel alloc]init]; label.numberOfLines = 0;//多行显示 label.backgroundColor = [UIColor yellowColor]; label.font = [UIFont systemFontOfSize:20]; NSString *string = @"我爱中国我爱中国我爱中国我爱中国我爱中国我爱中国我爱中国我爱中国我爱中国我爱中国我爱中国我爱中国"; UIFont *font = [UIFont systemFontOfSize:20]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.lineSpacing = 20;//行间距 NSDictionary *attributes = @{ NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle };//其他属性可以在UIKit的第一个头文件中查看,颜色。。 CGRect size = [string boundingRectWithSize:CGSizeMake(200, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];//iOS 7.0有效 NSAttributedString *attributeString = [[NSAttributedString alloc]initWithString:string attributes:attributes];//设置属性字体 label.frame = size; label.attributedText = attributeString; label.center = self.view.center; [self.view addSubview:label];
封装的方法:
- (CGSize)textSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode { CGSize textSize; if ([XWCHelper isIOS7orHigher]) { if (CGSizeEqualToSize(size, CGSizeZero)) { textSize = [self sizeWithAttributes:@{NSFontAttributeName:font}]; } else{ NSStringDrawingOptions option = NSStringDrawingUsesLineFragmentOrigin; //NSStringDrawingTruncatesLastVisibleLine如果文本内容超出指定的矩形限制,文本将被截去并在最后一个字符后加上省略号。 如果指定了NSStringDrawingUsesLineFragmentOrigin选项,则该选项被忽略 NSStringDrawingUsesFontLeading计算行高时使用行间距。(译者注:字体大小+行间距=行高) NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName]; CGRect rect = [self boundingRectWithSize:size options:option attributes:attributes context:nil]; textSize = rect.size; } } else{ if (CGSizeEqualToSize(size, CGSizeZero)) { textSize =[self sizeWithFont:font]; } else{ textSize =[self sizeWithFont:font constrainedToSize:size lineBreakMode:lineBreakMode]; } } return textSize; }
时间: 2024-10-27 09:44:37