Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView done button action - on return key

Tags:

ios

Using UITextView, how do you know when "Done" or other is pressed on the keyboard?

Do I need to look at every char in textViewDidChange and if so, what to look for?

IB selected UITextView:

enter image description here

like image 347
Chris G. Avatar asked Mar 04 '26 00:03

Chris G.


2 Answers

I just tested this. Seems to satisfy your requirement:

class ViewController: UIViewController, UITextViewDelegate {
    @IBOutlet weak var myTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
       myTextView.delegate = self
    }

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
    {
        if(text == "\n")
        {
            view.endEditing(true)
            return false
        }
        else
        {
            return true
        }
    }
}
like image 119
Martin Muldoon Avatar answered Mar 06 '26 12:03

Martin Muldoon


It is possible to do that in textViewDidChange by looking for a newline "\n".

Otherwise, a better idea would be to use func textView(UITextView, shouldChangeTextIn: NSRange, replacementText: String) by checking replacementText == "\n"

Example:

func textView(UITextView, shouldChangeTextIn: NSRange, replacementText: String){
    if replacementText == "\n"{
        // do your stuff here
        // return false here, if you want to disable user from adding newline
    }
    // otherwise, it will return true and the text will be replaced
    return true
}
like image 41
ramacode Avatar answered Mar 06 '26 14:03

ramacode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!