How to Toggle First Responders Between Text Fields and Views

I have a UIViewController with a UITextView and a UITextField.

The UITextField becomes a first responder upon the view loading:

override func viewDidAppear(_ animated: Bool) {
  super.viewDidAppear(animated)
  textField.becomeFirstResponder()
}

The problem is that I can't simply tap the UITextView and start editing. My guess is that I need to resign the first responder from the UITextField first.

I tried the UITextFieldDelegate methods for ending editing and adding the textField.resignFirstResponder() method, but that method isn't being triggered at all (based on a print statement not showing).

Here's an example of that approach:

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

I would like to ultimately toggle between these two text views while never dismissing the keyboard. So, the first responder status would simply be passed back and forth. But, I can't seem to find any methods that are essentially letting my fire a call to a method upon tapping.

Does anyone know what methods would allow this functionality?


Calling resignFirstResponder inside textFieldShouldEndEditing has no effect, since the function is only called when the textField is about to resign first responder. You should either use resignFirstResponder inside textFieldShouldReturn if you want to make editing end on the tap of the return key or override the UIViewController s touchesBegan method if you want to resign first responder when the user touches anywhere outside your `textField.

The resign first responder on hitting the return key method:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true    
}

if you are using on simulator iOS system keyboard sometimes does not appear... when you switch text Field or View keyboard wont disappear on real Device.. if you want to try on simulator Uncheck Connect hardware keyboard from simulator hardware option... 模拟器设置屏幕截图

链接地址: http://www.djcxy.com/p/44314.html

上一篇: 如何用Maven包装Ant构建?

下一篇: 如何在文本字段和视图之间切换第一个响应者