Swift: Become First Responder on UITextField Not Working?

只谈情不闲聊 提交于 2019-12-10 01:59:05

问题


I've created a custom UIViewController with one UITextField on Storyboard. On viewDidLoad, I set the UITextFIeld to becomeFirstResponder, nothing happened (no keyboards popped up).

I then tried calling resignFirstResponder(), but it returned false. Next I tried to find who the first responder is through looping all the subviews using the code over @ Get the current first responder without using a private API. It turns out none of the sub views are the first responder.

My ViewController in storyboard

My Code

class BLTestViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var tf: UITextField

    override func viewDidLoad() {
        super.viewDidLoad()

        tf.delegate = self
        tf.becomeFirstResponder()
        // Do any additional setup after loading the view.
    }
}

As simple as it gets...WHY ISN'T THE KEYBOARD COMING UP!!! One thing I do have on is auto layout, but I'm not sure if that affects the keyboard popping up.


回答1:


I just tested it with a textfield by calling self.tf.becomeFirstResponder() indside viewDidLoad() function and its working absolutely fine. You'll need to toggle your keyboard by pressing command + K as nflacco just pointed out and disable the hardware keyboard in the simulator as:

  1. iOS Simulator -> Hardware -> Keyboard
  2. Uncheck "Connect Hardware Keyboard"



回答2:


Swift 4 it worked for me
try it

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

    DispatchQueue.main.async {
        self.textView.becomeFirstResponder()
    }

}



回答3:


I think

class BLTestViewController: UIViewController, UITextFieldDelegate {

@IBOutlet var tf: UITextField

    override func viewDidLoad() {
        super.viewDidLoad()

        tf.delegate = self
        self.focustf()
        // Do any additional setup after loading the view.
    }

    func focustf(){
    self.tf.becomeFirstResponder()
    }
}



回答4:


Swift 4 and iOS 11

In my case, no mater what I tried, I was not able to set first responder until I tried this.

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if cell.isKind(of: YOURTABLEVIEWCELL.self) {
        if let yourCell = cell as? YOURTABLEVIEWCELL{
            yourCell.yourUiTextField.becomeFirstResponder()
        }
    }
}

Hope this helps someone stuck with the same problem.




回答5:


press command+shift+k for open the keyboard.




回答6:


try with this

 DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    textField.becomeFirstResponder()
                }

sometimes the wrong is the time in render the view



来源:https://stackoverflow.com/questions/25353687/swift-become-first-responder-on-uitextfield-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!