字符串替换 - 归因字符串

时间:2014-12-12 10:35:12

标签: ios8 uitextview nsattributedstring

这是我的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显示为属性字符串,条件为<strong></strong>为红色,这是我的代码。

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

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

1 个答案:

答案 0 :(得分:0)

以下代码为我做了:

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样式。