简体   繁体   中英

Changing text color in Attributed TextView (Xcode)

I am trying to change the color of a sentence in my TextView which is attributed. How do I go about this?

Say, I wanted to change the color of the first sentence to red.

在此处输入图片说明

When I click these buttons (the left is "Text Color" and the other is "Background Color") nothing happens. 在此处输入图片说明

You can achieve this by doing it programatically. Use NSMutableAttributedString

NSMutableAttributedString *stringText = [[NSMutableAttributedString alloc] initWithString:@"This is awesome"];
//Green color for the first four characters.
[stringText addAttribute: NSForegroundColorAttributeName value: [UIColor greenColor] range: NSMakeRange(0, 4)];
// Sets the font color of last four characters to yellow.
[stringText addAttribute: NSForegroundColorAttributeName value: [UIColor yellowColor] range: NSMakeRange(14, 10)];

Set this text to your UITextView. It should work. Also make sure if text changes dynamically you need to care full with NSMakeRange.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM