带有NSMutableAttributedString的NSMutableParagraphStyle

时间:2014-06-21 03:22:21

标签: objective-c uitextview uicolor nsmutableattributedstring

我有一个段落,我使用NSMutableParagraphStyle来管理行高。另外,我想在段落中改变一个单词的颜色,这是我使用的代码,但它只是改变一个单词的颜色(attributedText被覆盖)我该如何解决?任何帮助?

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

paragraphStyle.lineHeightMultiple = 1.45f;

paragraphStyle.alignment = UITextAlignmentRight;

NSDictionary *ats = @{
                      NSFontAttributeName            : [UIFont fontWithName:@"Helvetica"
                                                                      size:currentSize],
                      NSParagraphStyleAttributeName  : paragraphStyle,

                      };


ayaTxt.attributedText    = [[NSAttributedString alloc] initWithString:ayaTxt.text
                                                             attributes:ats];

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc]
                                         initWithString:ayaTxt.text];

NSRange range = [[AyatWords objectAtIndex:aya] rangeOfString:@":"];

[attrString addAttribute:NSForegroundColorAttributeName
                   value:[UIColor colorWithRed:(25.0/255.0)
                                         green:(168.0/255.0)
                                          blue:(167.0/255.0)
                                         alpha:1.0]
                   range:NSMakeRange(0, range.location + 1)];

ayaTxt.attributedText = attrString;

谢谢..

1 个答案:

答案 0 :(得分:5)

我解决了它:)

NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithString:wordsTxt.text];

NSRange range = [[AyatWords objectAtIndex:aya] rangeOfString:@":"];

NSRange wholeRange = NSMakeRange(0, as.length);

[as addAttribute:NSForegroundColorAttributeName
                   value:[UIColor colorWithRed:(25.0/255.0)
                                         green:(168.0/255.0)
                                          blue:(167.0/255.0)
                                         alpha:1.0]
                   range:NSMakeRange(0, range.location + 1)];

[as addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:currentSize]
                                     range:wholeRange];

NSMutableParagraphStyle *ps = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];

ps.lineHeightMultiple = 1.45f;

ps.alignment = UITextAlignmentRight;


[as addAttribute:NSParagraphStyleAttributeName value:ps range:wholeRange];

wordsTxt.attributedText = as;