swift label加载html预估高度

注意:如果html中包含图片链接则预估不准确.

+ (NSStringDrawingOptions)stringDrawingOptions{

return NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;

}

*options参数由于在swift中没找到正确的写法,所以我是oc类中定义了实现options多选的方法

do{

let htmlString = contentArry[0] as! String

let attributedStr = try NSMutableAttributedString(data: htmlString.dataUsingEncoding(NSUnicodeStringEncoding,allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)

let options : NSStringDrawingOptions = H5WebView.stringDrawingOptions()

attributedStr.addAttribute(NSDocumentTypeDocumentAttribute, value:UIFont.systemFontOfSize(16), range:NSMakeRange(0, attributedStr.length))

let rect = attributedStr.boundingRectWithSize(CGSizeMake(MAIN_SCREEN_WIDTH-60, 250), options: options, context: nil)//UsesLineFragmentOrigin

let htmlHeight = CGRectGetHeight(rect)

return htmlHeight

}catch let error as NSError {

yqLog(error.localizedDescription)

return 160

}catch {//加入一个空的catch,用于关闭catch。否则会报错:Errors thrown from here are not handled because the enclosing catch is not exhaustive

return 160

}

```

*后期有空的时候我会描述一个昨天填的坑:在tableView自定义cell用使用webView加载html,利用webView预加载获取webView的高,适配cell的高.

你可能感兴趣的:(swift label加载html预估高度)