ios - 如何获取带有html内容的字符串的字符串大小

标签 ios objective-c

我可以使用此方法获取字符串大小

[myString sizeWithAttributes:@{NSFontAttributeName :myFont}

但是,我的字符串有 HTML 内容,我尝试这样做

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

但是,我得到了错误的值? 我也尝试像这样使用 NSAttributedString

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

而且我得到了错误的值。

我的字符串是非常基本的 HTML 内容,例如它返回的“test & test 宽度为 15 个字符而不是 11

最佳答案

首先尝试删除 html 标签,以此作为引用 - Remove HTML Tags from an NSString on the iPhone

然后获取字符串大小,试试这个:

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));

关于ios - 如何获取带有html内容的字符串的字符串大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33409717/

相关文章:

ios - Swift 中的时间戳

ios - swift 错误 : Could not determine generated file paths for Core Data code generation:

ios - 没有来自 Interface Builder 的 UINavigationController 的 UINavigationBar

ios - 使用标记符号访问 UILabel

objective-c - iOS 应用程序更新,删除了一种本地化语言

Objective-C 整数运算

ios - Iphone 模拟器崩溃

ios - 没有返回值的 block

ios - 向后导航时相机进给卡住 - ios,objective-c

ios - 在 objective-c 中解析多行json