前端之家收集整理的这篇文章主要介绍了
OC/Swift 根据label字数字体返回实际高度,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Swift
let text = "用于管理内容的绘制有关的对象显示在一个滚动视图应该瓦片的内容的子视图,以便没有视图超过屏幕的大小。当用户在滚动滚动视图,这个对象应该添加和删除子视图是必要的。"
let attributesString = NSMutableAttributedString.init(string: text)
let paraghStyle = NSMutableParagraphStyle()
paraghStyle.lineSpacing = 10
attributesString.addAttributes([NSParagraphStyleAttributeName : paraghStyle],range: NSMakeRange(0,text.characters.count))
label.attributedText = attributesString
label.lineBreakMode = NSLineBreakMode.ByTruncatingTail
label.contentMode = UIViewContentMode.Top
let text: NSString = NSString(CString: text.cStringUsingEncoding(NSUTF8StringEncoding)!,encoding: NSUTF8StringEncoding)!
let attributes = [NSFontAttributeName:label.font]
let size = text.boundingRectWithSize(CGSizeMake(UIScreen.mainScreen().bounds.width - 60,CGFloat(MAXFLOAT)),options: NSStringDrawingOptions.UsesLineFragmentOrigin,attributes: attributes,context: nil).size
label.text = attributesString.string
print(size)
OC
NSString *text = @"用于管理内容的绘制有关的对象显示在一个滚动视图应该瓦片的内容的子视图,以便没有视图超过屏幕的大小。当用户在滚动滚动视图,这个对象应该添加和删除子视图是必要的。";
NSMutableAttributedString *attibutesString = [[NSMutableAttributedString alloc] initWithString:text];
NSMutableParagraphStyle *paraghStyle =[[NSMutableParagraphStyle alloc] init];
[paraghStyle setLineSpacing:10];
[attibutesString addAttribute:NSParagraphStyleAttributeName value:paraghStyle range:NSMakeRange(0,text.length)];
label.attributedText = attibutesString;
label.lineBreakMode = NSLineBreakByTruncatingTail;
[label setContentMode:UIViewContentModeTop];
NSDictionary *attribute = @{NSFontAttributeName:label.font,NSParagraphStyleAttributeName:paraghStyle};
CGSize labelSize = [text boundingRectWithSize:size options: NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
NSLog(@"%@",NSStringFromCGSize(labelSize));
原文链接:https://www.f2er.com/swift/323355.html