AutoLayout row height miscalculating for NSAttributedString

后端 未结 8 1631
时光取名叫无心
时光取名叫无心 2021-01-31 11:57

My app pulls HTML from an API, converts it into a NSAttributedString (in order to allow for tappable links) and writes it to a row in an AutoLayout table. Trouble i

8条回答
  •  长发绾君心
    2021-01-31 12:22

    You can replace this method to calculate the height of attributed string:

    - (CGFloat)textViewHeightForAttributedText:(NSAttributedString*)text andFont:(UIFont *)font andWidth:(CGFloat)width {
    CGFloat result = font.pointSize + 4;
    if (text)
        result = (ceilf(CGRectGetHeight([text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil])) + 1);
    
    return result;
    

    }

    Maybe the font you changed doesnt matches with the font of content on html pages. So, use this method to create attributed string with appropriate font:

    // HTML -> NSAttributedString

    -(NSAttributedString*) convertHTMLtoAttributedString: (NSString *) html {
    NSError *error;
    NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUTF8StringEncoding] options:options documentAttributes:nil error:&error];
    if(!attrString) {
        NSLog(@"creating attributed string from HTML failed: %@", error.debugDescription);
    }
    return attrString;
    

    }

    // force font thrugh & css

    - (NSAttributedString *)attributedStringFromHTML:(NSString *)html withFont:(UIFont *)font    {
    return [self convertHTMLtoAttributedString:[NSString stringWithFormat:@"%@", font.fontName, font.pointSize, html]];
    

    }

    and in your tableView:heightForRowAtIndexPath: replace it with this:

    case kContent:
            return [self textViewHeightForAttributedText:[self attributedStringFromHTML:myHTMLString withFont:contentFont] andFont:contentFont andWidth:self.tappableCell.width]; 
            break;
    

提交回复
热议问题