更改属性textview中的一个单词的颜色(objective-c)

时间:2015-10-21 23:08:49

标签: ios objective-c textview

我有一个带有Attributed文本的textview。我试图将属性文本的前14个字母("隐私政策")的颜色更改为存储值" appTintColor"。此应用色调颜色存储在p列表中,并且每个应用目标都有不同的颜色。

如何将textView的属性文本的前5个字母更改为此变量" appTintColor"?我知道我可以使用xCode界面轻松地将颜色更改为RGB / HEX颜色......但我想将此颜色更改为变量" appTintColor"这是基于应用目标的动态。

我是否在文本字段中添加了一个插座,下标前14个字符,并将其设置为appTintColor?这就是我的逻辑,但我似乎无法在代码中获得它。

enter image description here

1 个答案:

答案 0 :(得分:2)

您需要NSMutableAttributedString - 请尝试以下代码:

UIColor *color = [UIColor greenColor];

NSString *privacyPolicyFullStr = @"Privacy policy\n blah stuff things blah cat bat mongoose platypus";

NSMutableAttributedString *mutAttrStr = [[NSMutableAttributedString alloc]initWithString:privacyPolicyFullStr attributes:nil];

NSString *privacyPolicyShortStr = @"Privacy Policy"; //just to avoid using a magic number
NSDictionary *attributes = @{NSForegroundColorAttributeName:color};
[mutAttrStr setAttributes:attributes range:NSMakeRange(0, privacyPolicyShortStr.length)];

self.textView.attributedText = mutAttrStr; 
相关问题