简体   繁体   中英

How to get the string size of string with html content

I can get the string size using This method

[myString sizeWithAttributes:@{NSFontAttributeName :myFont}

but, my string has HTML content , I tried to do it like this

[myString sizeWithAttributes:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSFontAttributeName :myFont}

but,I got a wrong value ? also I tried to use NSAttributedString like this

NSAttributedString * tabText = [[NSAttributedString alloc] initWithData:[myString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,myFont: NSFontAttributeName} documentAttributes:nil error:nil];
CGSize mySize=[tabText size];

And also I got a wrong value .

my string is very basic HTML content like " test & test " it returns the width of 15 chars not 11

Try removing the html tags first, use this as reference - Remove HTML Tags from an NSString on the iPhone

Then get the string size, try this:

CGSize stringSize = [YOUR_STRING sizeWithAttributes: @{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]}];

// ceilf - is used to get equivalent values
CGSize currentSize = CGSizeMake(ceilf(stringSize.width), ceilf(stringSize.height));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM