如何在UITextView中为文本着色

时间:2016-04-05 10:32:38

标签: ios objective-c uitextview textkit

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

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

https://codex.wordpress.org/Child_Themes

怎么做?我已经按照本教程enter image description here

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

3 个答案:

答案 0 :(得分:1)

您需要使用NSAttributedString类。

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

答案 1 :(得分:1)

您可以使用NSMutableAttributedString来实现这一目标。这个想法是以下(我没有测试过,只是手写在这里):

NSString *str = @"stackoverflow";
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

答案 2 :(得分:1)

以下是我如何继续,如果它可以帮助你:

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];
   }