在UITextView中编辑文本时添加不同的颜色,而不管Swift

时间:2017-07-11 15:27:39

标签: ios swift uitextview nsattributedstring

我有一个textview,我预先填写了一些必要的注释,例如:"嗨这是John"会在textview中显示蓝色。现在我需要的是,无论在textview中进行任何新的编辑,它都会变成黑色。所以,如果我将文本编辑为"嗨这是Steve"。只有"史蒂夫"应该是黑色的,休息应该是蓝色的。我知道我将不得不使用NSAttributedString,但我该怎么做呢?

现在我在我的视图加载

上执行此操作
descriptionTextView.text = myString
descriptionTextView.textColor = UIColor.blue

这就是发短信

func textViewDidBeginEditing(_ textView: UITextView) {
    descriptionTextView.textColor = UIColor.black
}

但这会把一切变成黑色。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

您可以使用UITextViewDelegate

来实现此目的

UITextView设置委托,并将NSRange的全局变量设为:

IBOutlet UITextView *textVw;
NSRange textRange;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    UIColor *color = [UIColor blueColor]; // set initial needed color
    NSString *string = @"Hi this is John"; // set initial string to color
    NSDictionary *attrs = @{ NSForegroundColorAttributeName : color };
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:string attributes:attrs];
    textVw.attributedText = attrStr;

    //Set delegate of UITextView
    [textVw setDelegate:self];
}

#pragma UITextViewDelegate Methods.
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
     //Check string is written or backspace (with prediction on).
     if (text.length > 1) {

         //Make Range for black text in textview.
         textRange = NSMakeRange(range.location, text.length + 1);

         return YES;
     }

     //Check string is written or backspace.
     if (text.length > 0 && ![text isEqualToString:@" "]) {

         //Make Range for black text in textview.
         textRange = NSMakeRange(range.location, 1);

        return YES;
     }

    return YES;
}

-(void)textViewDidChange:(UITextView *)textView {

    //Check there are some value is written or not.
    if (textRange.length > 0) {

        //Check textview is rest with initial value or not.
        if ([textVw.text caseInsensitiveCompare:@"Hi this is John"] == NSOrderedSame) {

            //Rest value so make string as blue.
            UIColor *color = [UIColor blueColor]; // set initial needed color
            NSString *string = @"Hi this is John"; // set initial string to color
            NSDictionary *attrs = @{ NSForegroundColorAttributeName : color };
            NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:string attributes:attrs];
            textVw.attributedText = attrStr;

        } else {

            NSMutableAttributedString *text =
            [[NSMutableAttributedString alloc]
             initWithAttributedString: textVw.attributedText];

            [text addAttribute:NSForegroundColorAttributeName
                         value:[UIColor blackColor]
                         range:textRange];

            //Add new Attributed value to textView with black color.
            [textVw setAttributedText: text];

        }

        //After assign value to textfiled make textRange varibale as default value for safe handler.
        textRange = NSMakeRange(0, 0);
    }
}

- (void)textViewDidChangeSelection:(UITextView *)textView
{
      //Check there are some value is written or not.

      if (textRange.length > 1) {
             //For maintain cursor position with prediction on.
             [textView setSelectedRange:NSMakeRange(textRange.location + textRange.length , 0)];

      } else if (textRange.length > 0) {
            //For maintain cursor position.
            [textView setSelectedRange:NSMakeRange(textRange.location + 1, 0)];
      }
}

答案 1 :(得分:0)

试试这个:

类AViewController:UIViewController,UITextViewDelegate {

@IBOutlet var textView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()

    textView.delegate = self;
    textView.text = ""
    textView.textColor = UIColor.blue
}

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {


    let colorAttr = [NSForegroundColorAttributeName: UIColor.black, NSFontAttributeName: UIFont.systemFont(ofSize: 15)]

    let attributedString = NSMutableAttributedString(string: text, attributes: colorAttr)

    let combination = NSMutableAttributedString()

    combination.append(textView.attributedText!)
    combination.append(attributedString)
    textView.attributedText = combination

    return true

}

基本上,在点击新角色时始终会调用shouldChangeTextIn。使用NSMutableAttributedString,您可以使用新字符串轻松地将旧attributedString添加为黑色。

PS:您需要遵守UITextViewDelegate协议。