iosswiftuitextfield

Error when attempting to set a UITextField to first responder


I get this error when calling becomeFirstResponder() on a UITextfield:

-[RTIInputSystemClient remoteTextInputSessionWithID:performInputOperation:] perform input operation requires a valid sessionID. inputModality = Keyboard, inputOperation = , customInfoType = UIEmojiSearchOperations

When I initially create the textfield with this code:

textField = UITextField(frame: CGRect(origin: .zero, size:frame.size))
textField.text = ""
textField.backgroundColor = UIColor.clear
textField.layer.borderWidth = 0
textField.layer.borderColor = UIColor.clear.cgColor
textField.layer.backgroundColor = UIColor.clear.cgColor

And then set textField.becomeFirstResponder(). It works but if I tap off of the textfield I get the error above, and I get the same exact error when I attempt to tap the text field again. I've already attempted to turn of auto correct as was suggested in a similar post but that does nothing.

I've tried removing the textfield from the superview and creating a completely new one and adding that in it's place and I get the same error


Solution

  • Could you try the code this way?

    import UIKit
    
    class ViewController: UIViewController, UITextFieldDelegate {
    
    var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        setupTextField()
    }
    
    func setupTextField() {
        textField = UITextField(frame: CGRect(origin: .zero, size: CGSize(width: 200, height: 40)))
        textField.delegate = self
        textField.text = ""
        textField.backgroundColor = UIColor.clear
        textField.layer.borderWidth = 0
        textField.layer.borderColor = UIColor.clear.cgColor
        textField.layer.backgroundColor = UIColor.clear.cgColor
        self.view.addSubview(textField)
    
        DispatchQueue.main.async {
            self.textField.becomeFirstResponder()
        }
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
    
     }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event:UIEvent?) {
        self.view.endEditing(true) // Dismiss the keyboard when tapping outside the text field
       }
     }