简体   繁体   English

如何在 Swift3 中更改 UITextView 中文本字符串的颜色

[英]How to change color of text strings inside UITextView in Swift3

I have looked at some existing questions posts here and I tried to implement all code but ended up not being able to successfully implement any code.我在这里查看了一些现有的问题帖子,我尝试实现所有代码,但最终无法成功实现任何代码。 Actually, I think I comprehended how to change colors of some texts inside UITextView if a text is initially set, but what I do not understand is that when my UITextView began entering editing, it does not seem to be working properly at all.实际上,我想我已经理解了如何在初始设置文本的情况下更改UITextView中某些文本的颜色,但是我不明白的是,当我的UITextView开始进入编辑时,它似乎根本无法正常工作。 In the following, it is my attempted code that closely full fills my desired behaviour.在下面,我尝试的代码完全满足了我想要的行为。

 func textViewDidBeginEditing(_ textView: UITextView) {

    let main_string = ""
    let getData: [String] = userDefaults.object(forKey: "myData") as! [String]
    print("\(getData)")

    let searchWords = "world"

        let range = (main_string as NSString).range(of: searchWords)

        let attribute = NSMutableAttributedString.init(string: main_string)
        attribute.addAttribute(NSForegroundColorAttributeName, value: UIColor.red , range: range)

        mytextView.attributedText = attribute


}

I saved input data by naming MyData .我通过命名MyData保存输入数据。 I tried to use a for-loop to take all elements out of getData and use it as individual values.我尝试使用 for 循环从getData取出所有元素并将其用作单独的值。 However, in the console, there are so many lines of explanation.但是,在控制台中,有这么多行的解释。 I think this is a proper way to write, but my mac says nooooooo.我认为这是一种正确的写作方式,但我的 mac 说 nooooooo。 However, If I set a String inside main_string and searchWords , for example, "this is my question. I want people to help me from the world" in main_string and "world" in searchWords as written in the code.但是,如果我在main_stringsearchWords设置一个String ,例如, “这是我的问题。我希望人们从世界上帮助我” main_string 和 searchWords 中的“world”如代码中所写。 Then after the app is being loaded, on my text view the word, "world" is highlighted in red perfectly, but after the world word, all text is in red.然后在加载应用程序后,在我的文本视图中,“世界”这个词完美地以红色突出显示,但在世界这个词之后,所有文本都是红色的。 I do not understand why I am being tortured by this unknown bug.我不明白为什么我会被这个未知的错误折磨。

So What I want to accomplish is所以我想要完成的是

  1. from the saved date in my myData , I only want the stored words to be highlighted timely when users type in. For example, if a user types "hello" and "world".myData保存的日期来看,我只希望用户输入时及时突出存储的单词。例如,如果用户键入“hello”和“world”。 Then they are saved by myData and they are going to be highlighted only when typed.然后它们由myData保存,并且只有在输入时才会突出显示。 And switch back to the normal color when words which are not stored are typed.并在输入未存储的单词时切换回正常颜色。

I assume I lack some explanation.我想我缺乏一些解释。 If you need to know something, please point out for me.如果你需要知道什么,请帮我指出。 Thanks very much!!非常感谢!!

In this I have taken string "world" as example.在此,我以字符串“world”为例。 When you r typing in textview then This method is in working当您在 textview 中输入时,此方法正在起作用

func textViewDidChange(_ textView: UITextView) {
        let attrStr = NSMutableAttributedString(string:txtview.text)
        let inputLength = attrStr.string.characters.count
        let searchString = "world"
        let searchLength = searchString.characters.count
        var range = NSRange(location: 0, length: attrStr.length)

        while (range.location != NSNotFound) {
            range = (attrStr.string as NSString).range(of: searchString, options: [], range: range)
            if (range.location != NSNotFound) {
                attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location: range.location, length: searchLength))
                range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
                textView.attributedText = attrStr
            }
        }    
}

But when You have already set initial text of textview then use this method但是当您已经设置了 textview 的初始文本时,请使用此方法

func textViewDidBeginEditing(_ textView: UITextView) {
        //Just set your text as you set in textview
        let attrStr = NSMutableAttributedString(string: "hello world I ma jeckjklwefljlwjflkjwfkljelwfjklfgjwklfjlkwgjwlgkjwklsgjklsjgklsdjgkljdslkgjsdlkgjlksdjgldjsgldjskl world nsfhjklshfklhsllsd fgiw world")
        let inputLength = attrStr.string.characters.count
        let searchString = "world"
        let searchLength = searchString.characters.count
        var range = NSRange(location: 0, length: attrStr.length)

        while (range.location != NSNotFound) {
            range = (attrStr.string as NSString).range(of: searchString, options: [], range: range)
            if (range.location != NSNotFound) {
                attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location: range.location, length: searchLength))
                range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
                textView.attributedText = attrStr
            }
          }  
  }

For Multiple Strings, You can do like this SWIFT 3对于多个字符串,您可以这样做 SWIFT 3

func textViewDidChange(_ textView: UITextView) {
        let attrStr = NSMutableAttributedString(string: txtview.text)
        let inputLength = attrStr.string.characters.count
        let searchString : NSArray = NSArray.init(objects: "hello","world")
        for i in 0...searchString.count-1
        {

             let string : String = searchString.object(at: i) as! String
             let searchLength = string.characters.count
             var range = NSRange(location: 0, length: attrStr.length)

             while (range.location != NSNotFound) {
                 range = (attrStr.string as NSString).range(of: string, options: [], range: range)
                 if (range.location != NSNotFound) {
                 attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location: range.location, length: searchLength))
                 range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
                 textView.attributedText = attrStr
        }
    }   
  }
}

OBJECTIVE C目标 C
For Multiple Strings, You can do like this对于多个字符串,您可以这样做

-(void)textViewDidChange:(UITextView *)textView
{
    NSMutableAttributedString *attstr = [[NSMutableAttributedString alloc]initWithString:textView.text];
    NSUInteger characterCount = [attstr length];
    NSArray *arr = [[NSArray alloc]initWithObjects:@"football",@"player",nil];

    for (int i=0; i<arr.count; i++) {

    NSUInteger searchlength = [[NSString stringWithFormat:@"%@",[arr objectAtIndex:i]] length];
    NSRange range1 = NSMakeRange(0, attstr.length);

    while (range1.location != NSNotFound) {
        range1 =[attstr.string rangeOfString:[NSString stringWithFormat:@"%@",[arr objectAtIndex:i]] options:0 range:range1];
        if (range1.location !=NSNotFound) {
            [attstr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(range1.location, searchlength)];
            [attstr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0]  range:range1];
            range1 = NSMakeRange(range1.location + range1.length, characterCount -(range1.location + range1.length));
            textView.attributedText = attstr;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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