【发布时间】:2013-11-28 07:43:31
【问题描述】:
我编写了一个方法来突出段落中的一个单词,方法是向它发送该单词的NSString,在我遇到这种情况之前它工作得很好:
当我有这段文字时:
他们的母亲曾尝试给他们穿其他衣服......
当我传递单词other 时,单词“mother”被突出显示,当我传递in 时,我得到了“dressing”。
这是我的代码:
-(void)setTextHighlited :(NSString *)txt{
NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:self.textLabel.text];
for (NSString *word in [self.textLabel.text componentsSeparatedByString:@" "]) {
if ([word hasPrefix:txt]) {
NSRange range=[self.textLabel.text rangeOfString:word];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
}
我已尝试将 rangeOfString:options: 与它的所有选项一起使用,但仍然遇到同样的问题。
请指教
【问题讨论】:
-
NSRegularExpression可能是解决方案。范围返回是rangeOfString的正常行为。 -
任何例子\
-
@HashmatKhalil 我需要使用 NSRange 而不是 NSPredicate 的解决方案!
-
有点冗长,但有一些使用 NSRegularExpression 的例子。无论如何,Tut 似乎适合你正在做的事情。
标签: ios objective-c nsstring nsattributedstring nsrange