如何在 UITextView 中为文本着色

How to color text in UITextView

我在视图控制器和一个文本视图上有四个按钮。这五个按钮有颜色,例如红色、黄色、绿色、蓝色和黑色。

当用户开始输入而不按下这些按钮时,正在输入的文本视图的颜色应该是黑色文本。如果用户按下红色按钮,则从该点开始的文本颜色应为红色,直到用户按下任何其他彩色按钮。

如何做到这一点?我遵循了本教程 https://www.objc.io/issues/5-ios7/getting-to-know-textkit/

但不知道如何将其定制为我想要实现的目标。

您需要使用 NSAttributedString class.

let defaultAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(UIFont.systemFontSize()),
                         NSForegroundColorAttributeName: UIColor.blackColor()]
let text = "this text is red and yellow"
let str = NSMutableAttributedString(string: text, attributes: defaultAttributes)
str.setAttributes([NSForegroundColorAttributeName: UIColor.redColor()], range: (text as NSString).rangeOfString("red"))
str.setAttributes([NSForegroundColorAttributeName: UIColor.yellowColor()], range: (text as NSString).rangeOfString("yellow"))
textView.attributedText = str

您可以使用 NSMutableAttributedString 来实现。思路如下(没测试,手写到这里):

NSString *str = @"Whosebug";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];

// Set foreground color of "stack" substring in our string to red
[attributedString addAttribute:NSForegroundColorAttributeName
  value:[UIColor redColor];
  range:NSMakeRange(0, 5)];

使用此方法,您可以实现将颜色应用于文本中所需范围的效果。

您可以像这样为您的 UILabel 设置属性文本:

yourLabel.attributedText = attributedString

如果对你有帮助的话,我是这样处理的:

1- add one property to retain current Color  and initialize it with black color 

 @property (nonatomic, retain) UIColor *curColor;//in your interface declaration

self.curColor = [UIColor blackColor];//Init it in Viewdidload for example

2- 实现 UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{

    NSAttributedString *currentText = self.Textview.attributedText;//To store current text and its attributs
    NSAttributedString *newOneText = [[NSAttributedString alloc] initWithString:text attributes:@{NSForegroundColorAttributeName:self.curColor}];//for the new text with selected color

    NSMutableAttributedString  *shouldDisplayText = [[NSMutableAttributedString alloc] initWithAttributedString: currentText];

    [shouldDisplayText appendAttributedString: newOneText];// add old and new text

    self.Textview.attributedText = shouldDisplayText;//set it ton control


    return NO;
}

3- 添加用于更改颜色的 IBAction =>

 - (IBAction) redColorClicked
    {
     self.curColor = [UIColor colorWithRed:1.0f green: 0.0f blue:0.0f alpha:1.0f];
   }

- (IBAction) blueColorClicked
        {
         self.curColor = [UIColor colorWithRed:0.0f green: 0.0f blue:1.0f alpha:1.0f];
   }