属性文本的高度未返回

时间:2017-08-19 15:12:39

标签: ios objective-c uitableview nsstring nsattributedstring

我需要在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")
            }
        }
    }

}

enter image description here

对于宽度343,高度为915,这是不准确的。

1 个答案:

答案 0 :(得分:1)

您可以使用boundingRectWithSize

 NSAttributedString *attrStr = [[NSAttributedString alloc]initWithString:@"<p>The HTML <strong>&lt;strong&gt;</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));