2015-03-02 70 views
0

我正在做Facebook这样的标记功能,并且我已经可以标记用户了。我可以像这样展示。它由这个代码完成。NSMutableAttributedString知道哪些文本的颜色被改变

NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:self.textView.text]; 

for (NSString *word in self.tagNameCollection) { 
    [string addColor:[UIColor redColor] substring:word]; 
    [string addBackgroundColor:[Helpers getFromRGB:135 green:206 blue:250] substring:word]; 
} 

所以,我有NSMutableAttributedString。我可以知道我在哪里更改颜色,从我的NSMutableAttributedString字体?我可以知道该怎么办?

enter image description here

+1

Lookt在'enumerateAttributesInRange:选择:usingBlock:' – Larme 2015-03-02 08:52:38

回答

2

您可以使用enumerateAttributesInRange:options:usingBlock:让你有什么NSAttributedString的属性。

实施例:

[attributedString enumerateAttributesInRange:NSMakeRange(0, [attributedString length]) 
            options:0 
            usingBlock:^(NSDictionary *attributes, NSRange range, BOOL *stop) { 
if ([attributes objectForKey:NSForegroundColorAttributeName]) 
    NSLog(@"Found ForeGround Color: %@ in range %@", [attributes objectForKey:NSForegroundColorAttributeName], NSStringFromRange(range)); 
if ([attributes objectForKey:NSFontAttributeName]) 
    NSLog(@"Found Font: %@ in range %@", [attributes objectForKey:NSFontAttributeName], NSStringFromRange(range)); 
if ([attributes objectForKey:NSBackgroundColorAttributeName]) 
    NSLog(@"Found Background Color: %@ in range %@", [attributes objectForKey:NSBackgroundColorAttributeName], NSStringFromRange(range)); 

}]; 
+0

感谢。看起来没问题。我是否总是需要保留NSMutableAttributedString,并在uitextview中更改某些内容时进行更新?我可以从我的uitextview获取NSMutableAttributedString吗?如果我这样做,NSMutableAttributedString的属性就消失了。 NSMutableAttributedString * muStr = [[NSMutableAttributedString alloc] initWithString:self.inputToolBarViewInDetail.textView.text]; – 2015-03-02 09:21:34

+0

如果您想知道更改,您可能需要保留前一个参考,或者在修改文本时检查“UITextViewDelegate”方法。 – Larme 2015-03-02 10:59:10