becomeFirstResponder在iOS 8中不起作用
我正在使用UITextField的方法becomeFirstResponder来显示键盘。 这适用于iOS 7.但在iOS 8中,此方法不显示键盘。
UITextField *txtAddNew = [[UITextField alloc] initWithFrame:CGRectMake(10,10,240, 21)]; txtAddNew.font = [UIFont fontWithName:@"Helvetica" size:16]; txtAddNew.clearButtonMode = UITextFieldViewModeWhileEditing; txtAddNew.returnKeyType = UIReturnKeyDone; txtAddNew.delegate = self; txtAddNew.autocorrectionType = UITextAutocorrectionTypeNo; txtAddNew.tag = 15; // Open keyboard [txtAddNew becomeFirstResponder];
在iOS 8中有什么办法吗?
尝试像下面一样调用becomeFirstResponder
[txtAddNew performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0];
按照Apple,
如果当前响应者可以辞退第一响应者状态(canResignFirstResponder)并且新响应者可以成为第一响应者,则响应者对象仅成为第一响应者。
您可以调用此方法来创建响应者对象,例如查看第一响应者。 但是,如果它是视图层次结构的一部分,则只应在该视图上调用它。 如果视图的window属性包含UIWindow对象,则它已安装在视图层次结构中; 如果它返回nil,则视图将从任何层次结构中分离。
斯威夫特3
这是接受答案的快速3版本。 让我上class,我也不得不加延迟。
txtAddNew.perform( #selector(becomeFirstResponder), with: nil, afterDelay: 0.1 )
我想你错过了将addsubview
的txtAddNew
到Mainview
txtAddNew.tag = 15; [self.view addsubview:txtAddNew]; // Open keyboard [txtAddNew becomeFirstResponder];
有时首先让第一个响应者辞职是有帮助的:
var tapGesture = UITapGestureRecognizer() tapGesture.rac_gestureSignal().subscribeNext { [weak self] (_) -> Void in self?.inputTextField.resignFirstResponder() self?.inputTextField.becomeFirstResponder() } self.charViewsContainer.addGestureRecognizer(tapGesture)
在代码中添加此行。 我希望它能奏效
[txtAddNew performSelectorOnMainThread:@selector(becomeFirstResponder) withObject:nil afterDelay:0.0];
对于iOS 9.3,以下内容适用于我:
private var searchTextFieldShouldReturn = false override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.searchTextFieldShouldReturn = false self.searchTextField.becomeFirstResponder() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.searchTextFieldShouldReturn = true self.searchTextField.resignFirstResponder() } func textFieldShouldReturn(textField: UITextField) -> Bool { self.searchTextFieldShouldReturn = true textField.resignFirstResponder() return true } func textFieldShouldEndEditing(textField: UITextField) -> Bool { return self.searchTextFieldShouldReturn }
所以你需要确保你也实现了textFieldShouldEndEditing委托。
万一其他人和我有同样的问题:
我有一个IBOutlet
连接到我的UITextField
。 我错误地在viewDidLoad
方法中初始化它。 也就是说, [[textField alloc] init];
。 我删除了这一切,一切都恢复了。
Swift 4和iOS 11
在我的情况下,没有我尝试过的东西,在我尝试之前我无法设置第一响应者。
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() } } }
希望这有助于有人遇到同样的问题。