Search code examples
iosswiftuitextviewnsattributedstring

How can I call a custom function when the return button is pressed within a UITextView?


I'm trying to debug a problem where pressing the return key doesn't trigger a text view change and as a result messes with my NSAttributedString inside of my UITextView. Whenever I press the return button my UITextView calculates the number of lines and for whatever reason thinks the image is only 1 line.


Solution

  • You can call a custom function with the textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String).

    class ViewController: UIViewController, UITextViewDelegate {
    
        @IBOutlet weak var textView: UITextView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
    
            textView.delegate = self
        }
    
        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    
            if text == "\n" {
                print("new line")
                // Call your custom function
            }
    
            return true
        }