【问题标题】:String replace - Attributed string字符串替换 - 属性字符串
【发布时间】:2014-12-12 10:35:12
【问题描述】:

这是我的 HTML 响应

<p><strong>Ezekiel 33:1-20&nbsp;<br /><br /></strong>
<strong><sup>1</sup></strong> The word of the&nbsp;Lord&nbsp;came to me:&nbsp;<strong><sup>2&nbsp;</sup></strong>
&ldquo;Son of man, speak to your people and tell them: Suppose I bring the sword against a land, and the people of that land select a man from among them, appointing him as their watchman,&nbsp;
<strong><sup>3&nbsp;</sup></strong>

我想在 UITextView 中将上述 HTML 显示为属性字符串,条件为 &lt;strong&gt;&lt;/strong&gt; 为红色,这是我的代码。

attributedString2 = [[NSMutableAttributedString alloc] initWithData:[[NSString stringWithFormat:@"%@",readingPartCntnt] 
dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } 
   documentAttributes:nil error:nil];
    NSRange rang = [readingPartCntnt rangeOfString:@"<strong>" options:NSBackwardsSearch];
if (rang.location == NSNotFound) {
    NSLog(@"string was not found");
} else {
    NSLog(@"position %lu", (unsigned long)rang.location);
}
NSRange rang1 = [readingPartCntnt rangeOfString:@"</strong>" options:NSBackwardsSearch];
if (rang1.location == NSNotFound) {
    NSLog(@"string was not found");
} else {
    NSLog(@"position %lu", (unsigned long)rang1.location);
}

[attributedString2 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:rang];
[attributedString2 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:rang1];

它没有正确应用。请帮我解决。

【问题讨论】:

  • 我建议用原始字符串中的红色标记替换强标记,使用 NSAttritedString 方法读取它。

标签: ios8 uitextview nsattributedstring


【解决方案1】:

下面的代码为我做了:

readingPartCntnt = [readingPartCntnt stringByReplacingOccurrencesOfString:@"<strong>" withString:@"<strong style=\"color: red;\">"];

attributedString2 = [[NSMutableAttributedString alloc] initWithData:[[NSString stringWithFormat:@"%@",readingPartCntnt] 
    dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } 
    documentAttributes:nil error:nil];

self.textView.attributedText = attributedString2.copy;

这将在创建属性字符串之前更改原始字符串的 CSS 样式。

【讨论】:

    猜你喜欢
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 2017-04-24
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多