1

Can I use a String and NSMutableAttributedString in the same UITextView?

I am importing a .docx file and converting to String I am then displaying that in a UITextField however I want to colour specific words. Ideally the user would type "LineBreak" and it would automatically change the word LineBreak to a different colour

It is my understanding this will need to use NSMutableAttributedString however I don't know how to go about doing this

let string = "Test Specific Colour LineBreak TestLine2"
let attributedString = NSMutableAttributedString.init(string: string)
let range = (string as NSString).range(of: "LineBreak")
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, 
value: UIColor.blue, range: range)
txtView.attributedText = attributedString

So using the example above, I want to have the colour of "LineBreak" change whenever it is typed. The above works to change the colour but not every time I type it. I need to recognise that the string "LineBreak" is present and change its colour

What is the best way to achieve what I'm after?

elevate
  • 147
  • 7

2 Answers2

0

here is a way to achieve what you want

// set your textview delegate in your view controller if you are using textview
// set the target if you are using textfield
// textfield.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)

class ViewController: UIViewController,UITextViewDelegate {

@IBOutlet weak var textfield: UITextField!
@IBOutlet weak var txtView: UITextView!
override func viewDidLoad() {
    super.viewDidLoad()
    txtView.delegate = self
    textfield.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)

    // Do any additional setup after loading the view.
}


// if you are using textview implement this

func textViewDidChange(_ textView: UITextView) {
    print(textView.text)
    let string = textView.text

    if textView.text.contains("LineBreak") {
        let attributedString = NSMutableAttributedString.init(string: textView.text)
        let range = (string as! NSString).range(of: "LineBreak")
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor,
        value: UIColor.blue, range: range)
        textView.attributedText = attributedString
    }

}

// if you are using textfield you need to
// add this line in your didload
//textfield.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
// and implement this function

@objc func textFieldDidChange() {
    let string = textfield.text

    if textfield.text!.contains("LineBreak") {
        let attributedString = NSMutableAttributedString.init(string: textfield.text!)
               let range = (string as! NSString).range(of: "LineBreak")
               attributedString.addAttribute(NSAttributedString.Key.foregroundColor,
               value: UIColor.blue, range: range)
               textfield.attributedText = attributedString
           }
    }
}

output:

enter image description here

Wassim Ben Hssen
  • 519
  • 6
  • 23
0

Here's one approach to get you started...

Make sure your controller conforms to UITextViewDelegate and you've assigned the text view's delegate:

class ExampleViewController: UIViewController, UITextViewDelegate {

    @IBOutlet var theTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        theTextView.delegate = self
        theTextView.text = "Test Specific Colour LineBreak TestLine2 linebreak and another LineBreak occurance"
        formatTextInTextView(theTextView)
    }

    func textViewDidChange(_ textView: UITextView) {
        formatTextInTextView(textView)
    }

    func formatTextInTextView(_ textView: UITextView) -> Void {
        guard let curText = textView.text else { return }

        let bScroll = textView.isScrollEnabled
        textView.isScrollEnabled = false
        let selRange = textView.selectedRange

        let attributedString = NSMutableAttributedString.init(string: curText)

        let regex = try! NSRegularExpression(pattern: "LineBreak", options: [.caseInsensitive])
        let items = regex.matches(in: curText, options: [], range: NSRange(location: 0, length: curText.count))
        let ranges: [NSRange] = items.map{$0.range}
        for r in ranges {
            attributedString.addAttribute(.foregroundColor, value: UIColor.red, range: r)
        }
        textView.attributedText = attributedString
        textView.selectedRange = selRange
        textView.isScrollEnabled = bScroll
    }

}

You may want to limit it to case-sensitive, whole-word, etc...

DonMag
  • 69,424
  • 5
  • 50
  • 86