Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect text view begin editing and end editing in swift 3

Tags:

textview

swift

I found related questions and answers in objective-c but I couldn't find a proper way to this with swift? Is there methods to detect for text view same as text filed in swift?

I want to solve the issue hiding text view by keyboard. For that I need a way to detect start and end edit text view.

Any help would be appreciated. Note: I'm using swift 3.

like image 482
Zusee Weekin Avatar asked Jan 05 '17 02:01

Zusee Weekin


2 Answers

Just as Bawpotter said, "Use the delegate methods for UITextView". Here is what they look like in Swift 3:

func textViewDidBeginEditing(_ textView: UITextView) {

  // Run code here for when user begins type into the text view

}

func textViewDidEndEditing(_ textView: UITextView) {

  // Run code here for when user ends editing text view

}

Also make sure your UITextView's delegate is set to self or wherever these methods are in your app

like image 134
Garret Kaye Avatar answered Nov 15 '22 05:11

Garret Kaye


Conform your ViewController class to UITextViewDelegate and then write textView.delegate = self in your viewDidLoad(). After that write delegate methods for your textView as:

func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
     //  your code here
}

func textViewDidBeginEditing(_ textView: UITextView) {
    //  your code here
}

func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
     //  your code here
}

func textViewDidEndEditing(_ textView: UITextView) { 
   // your code here
}
like image 22
Ashvini Avatar answered Nov 15 '22 06:11

Ashvini