Josh O'Connor
Josh O'Connor

Reputation: 4962

Change color of one word in attributed textview (objective-c)

I have a textview with an Attributed text. I am trying to change the color of the first 14 letters ("Privacy Policy") of the attributed text to a stored value, "appTintColor". This app tint color is stored in the p list and has a different color for each app target.

How do I change the first 5 letters of the textView's attributed text to this variable "appTintColor"? I know I can change the color to an RGB/HEX color easily using the xCode interface... But I want to change this color to the variable "appTintColor" which is dynamic based on the app target.

Do I add an outlet to the textfield, subscript the first 14 characters, and set it to appTintColor? That is the logic I have but I can't seem to get it in code.

enter image description here

Upvotes: 2

Views: 846

Answers (1)

Rich Tolley
Rich Tolley

Reputation: 3842

You need an NSMutableAttributedString - try the following code:

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; 

Upvotes: 2

Related Questions