[英]Swift: Become First Responder on UITextField Not Working?
I've created a custom UIViewController with one UITextField on Storyboard.我在 Storyboard 上创建了一个带有一个 UITextField 的自定义 UIViewController。 On
viewDidLoad
, I set the UITextFIeld to becomeFirstResponder
, nothing happened (no keyboards popped up).在
viewDidLoad
,我将 UITextFIeld 设置为becomeFirstResponder
,什么也没发生(没有键盘弹出)。
I then tried calling resignFirstResponder()
, but it returned false.然后我尝试调用
resignFirstResponder()
,但它返回 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 .接下来,我尝试通过使用代码循环所有子视图来查找
first responder
是谁, 而不是使用私有 API 获取当前第一响应者。 It turns out none of the sub views are the first responder.事实证明,没有一个子视图是第一响应者。
My ViewController in storyboard我在故事板中的 ViewController
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.
我所做的一件事是自动布局,但我不确定这是否会影响键盘弹出。
Swift 4 it worked for me Swift 4 对我有用
try it尝试一下
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
textView.becomeFirstResponder()
}
I just tested it with a textfield by calling self.tf.becomeFirstResponder()
indside viewDidLoad()
function and its working absolutely fine.我只是通过调用
self.tf.becomeFirstResponder()
indside viewDidLoad()
函数使用文本字段对其进行了测试,并且它的工作非常好。 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:正如 nflacco 刚刚指出的那样,您需要通过按command + K来切换键盘,并禁用模拟器中的硬件键盘,如下所示:
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()
}
}
Swift 4 and iOS 11斯威夫特 4 和 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.希望这可以帮助遇到同样问题的人。
按 command+shift+k 打开键盘。
try with this试试这个
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
textField.becomeFirstResponder()
}
sometimes the wrong is the time in render the view有时错误的是渲染视图的时间
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.