我需要在UITableViewCell中显示文本,并需要设置tableView的高度。我使用以下方法动态计算行的高度。但是高度远远高于实际高度。
+(NSAttributedString *)getAttributedText:(NSString *)text {
NSMutableAttributedString *attrHTMLText = [[[NSAttributedString alloc] initWithData:[text dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil] mutableCopy];
[attrHTMLText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"OpenSans" size:14.0] range:NSMakeRange(0, attrHTMLText.length)];
[attrHTMLText addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, attrHTMLText.length)];
return attrHTMLText;
}
我将文字转换为归属文字的原因是因为普通文字具有HTML内容和换行符'& nbsp'在场。
var sys = {
users: [
{user: 'user1', pass: 'qwerty'},
{user: 'Ragnar', pass: 'lothbrok'},
{user: 'guest', pass: 'guest'}
],
valid: function(){
var userInp = document.getElementById("userInp").value;
// var pwInp = document.getElementById("pwInp").value;
var check = false;
for (var i=0; i < sys.users.length; i++ ){
if (userInp == sys.users.user /*&& apwInp == 'sys.users{pass}'*/) {
alert ("logged in")
} else {
alert ("no match")
}
}
}
}
对于宽度343,高度为915,这是不准确的。
答案 0 :(得分:1)
您可以使用boundingRectWithSize
NSAttributedString *attrStr = [[NSAttributedString alloc]initWithString:@"<p>The HTML <strong><strong></strong> element defines <strong>strong</strong>text, with added semantic importance.</p>"];
// your attributed string
CGFloat width = 200; // whatever your desired width is
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];;
NSLog(@"%@",NSStringFromCGRect(rect));