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

Adding different color while editting text in UITextView irrespective of cursor position in Swift

我有一个文本视图,我在其中预先填充了一些必需的注释,例如:"Hi this is John" 会在文本视图中显示为蓝色。现在我需要的是,无论在 textview 中进行什么新编辑,它都会以黑色显示。因此,如果我将文本编辑为 "Hi this is Steve"。只有 "Steve" 应该是黑色的,其余的应该是蓝色的。我知道我将不得不使用 NSAttributedString,但我该怎么做呢?

现在我在加载视图时执行此操作

descriptionTextView.text = myString
descriptionTextView.textColor = UIColor.blue

这是关于文本编辑的

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

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

试试这个:

class 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 协议。

您可以使用 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)];
      }
}