OC/Swift 根据label字数字体返回实际高度

前端之家收集整理的这篇文章主要介绍了OC/Swift 根据label字数字体返回实际高度前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Swift

let text = "用于管理内容的绘制有关的对象显示在一个滚动视图应该瓦片的内容的子视图,以便没有视图超过屏幕的大小。当用户在滚动滚动视图,这个对象应该添加删除子视图是必要的。"
//创建NSMutableAttributedString
let attributesString = NSMutableAttributedString.init(string: text)

//创建NSMutableParagraphStyle
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

//**把String转换成NSString,为了使用boundingRectWithSize方法计算实际行高**
let text: NSString = NSString(CString: text.cStringUsingEncoding(NSUTF8StringEncoding)!,encoding: NSUTF8StringEncoding)!
let attributes = [NSFontAttributeName:label.font]

//用NSString的boundingRectWithSize方法
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};

    //boundingRectWithSize取代了sizeWithFont方法
    CGSize labelSize = [text boundingRectWithSize:size options: NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;

    NSLog(@"%@",NSStringFromCGSize(labelSize));

猜你在找的Swift相关文章