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的高.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容