iosswiftuitextfielddelegateuitextviewdelegateresignfirstresponder

Swift resigning TextView from first responder


I have a TextField and a TextView in my ViewController. The ViewController follows both UITextFieldDelegate and UITextViewDelegate and their delegate methods.

I want to resign the TextField or the TextView from being the first responder when the return button is clicked. I implemented func textFieldShouldReturn(_ textField: UITextField) -> Bool func textFieldDidEndEditing(_ textField: UITextField) func textViewShouldReturn(_ textView: UITextView) -> Bool func textViewDidEndEditing(_ textView: UITextView) and have textField.resignFirstResponder() + textView.resignFirstResponder() in the corresponding ShouldReturn method.

When I click the return button, the TextField resigns successfully and the keyboard hides away; in the case of the TextView, the return button simply adds a new line to the TextView; the textViewShouldReturn(_:) doesn't get called at all.

Can someone please explain the difference between textFieldShouldReturn(_:) and textViewShouldReturn(_:) and how can I resign the TextView from being the first responder?

Thanks

import UIKit

class DetailViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate {

@IBOutlet weak var date: UITextField!
@IBOutlet weak var noteText: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()

    date.delegate = self
    noteText.delegate = self
}


//MARK: UITextViewDelegate

func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
    // Hide the keyboard.
    textView.resignFirstResponder()
    return true
}


func textViewDidEndEditing(_ textView: UITextView) {
}

func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
    // Hide the keyboard.
    textField.resignFirstResponder()
    return true
}


func textFieldDidEndEditing(_ textField: UITextField) {
}

}

Solution

  • There is a trick to resign textview.

    extension ViewController: UITextViewDelegate {
        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    
            if text == "\n" {
                textView.resignFirstResponder()
                return false
            }
            return true
        }
    }
    

    Make sure to set your ViewController as textview's delegate