html 转换为string,NSAttributedString和HTMLString之间的转换

bb76f68fa61b

自制富文本编辑器

NSAttributedString to HTMLString

NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};

NSData *htmlData = [attributeString dataFromRange:NSMakeRange(0, attributeString.length) documentAttributes:documentAttributes error:NULL];

NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];

HTMLString to NSAttributedString

NSAttributedString* attributeString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]

options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,

NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}

documentAttributes:nil error:nil];

注意事项:

NSAttributedString 转为htmlstring后,再转换回NSAttributedString字体会变大,经过查找资料发现是系统问题。stackoverflow上面给出了解决办法:

static CGFloat const kListsLeading = 10.0;

static CGFloat const kListsAdditionalShift = 4.0;

+ (NSAttributedString *)decreaseFontSizeBecauseOfAppleMagic:(NSAttributedString *)astr

{

NSMutableAttributedString *mastr = [astr mutableCopy];

[mastr enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, astr.length) options:0 usingBlock:^(UIFont *_Nullable value, NSRange range, BOOL *_Nonnull stop) {

if (value) {

UIFont *font = [value fontWithSize:value.pointSize * 0.75];

[mastr addAttribute:NSFontAttributeName value:font range:range];

}

}];

[mastr enumerateAttribute:NSParagraphStyleAttributeName inRange:NSMakeRange(0, astr.length) options:0 usingBlock:^(NSParagraphStyle *_Nullable value, NSRange range, BOOL *_Nonnull stop) {

if (value) {

NSMutableParagraphStyle *style = [value mutableCopy];

style.minimumLineHeight *= 0.75;

if (style.firstLineHeadIndent == style.headIndent) {

style.firstLineHeadIndent *= 0.75;

style.headIndent *= 0.75;

}

else if (style.firstLineHeadIndent < kListsLeading) {

CGFloat shift = (kListsLeading - style.firstLineHeadIndent);

style.headIndent += shift + kListsAdditionalShift;

style.firstLineHeadIndent = kListsLeading;

NSMutableArray *tabs = [NSMutableArray array];

NSInteger index = 0;

for (NSTextTab *tab in style.tabStops) {

[tabs addObject:[[NSTextTab alloc] initWithTextAlignment:tab.alignment location:tab.location + shift + kListsAdditionalShift * (index ? 1 : 0) options:tab.options]];

index++;

}

style.tabStops = tabs;

}

style.tailIndent *= 0.75;

[mastr addAttribute:NSParagraphStyleAttributeName value:style range:range];

}

}];

return [mastr copy];

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值