我有相当多的控件分散在我的表格中的许多表格单元格中,我想知道是否有一种更简单的方法来消除键盘,而不必循环遍历所有的控件并将它们全部辞职为第一响应器。我想问题是…我如何得到当前的第一个响应器的键盘?
当前回答
Try:
[self.view endEditing:YES];
其他回答
您可以递归地遍历子视图,存储所有UITextFields的数组,然后循环遍历它们并重新分配它们。
这并不是一个很好的解决方案,特别是当你有很多子视图时,但对于简单的应用程序来说,它应该是可行的。
我用一种更复杂,但更高效的方式解决了这个问题,但使用了我的应用程序的动画引擎的单例/管理器,任何时候一个文本字段成为响应器,我会将它分配给一个静态,它会根据某些其他事件被清除(辞职)…我几乎不可能用一段话解释清楚。
要有创意,在我发现这个问题后,我只花了10分钟就考虑了这个问题。
您可以使用[view ended:YES]强制当前正在编辑的视图放弃其第一响应器状态。这样就隐藏了键盘。
与-[UIResponder resignFirstResponder]不同,-[UIView enditing:]将通过子视图搜索当前的第一响应器。所以你可以把它发送到顶层视图(比如self)。UIViewController中的view)它会做正确的事情。
(这个答案之前包含了几个其他的解决方案,它们也可以工作,但比必要的更复杂。为了避免混淆,我把它们去掉了。)
你可以向应用程序发送一个nil目标动作,它会在任何时候辞职第一响应者,而不必担心哪个视图当前有第一响应者状态。
objective - c:
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
斯威夫特3.0:
UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil)
在Mac OS X中,Nil目标操作在菜单命令中很常见,在iOS中也有使用。
比Meagar的回答更简单
覆盖touchesBegan: withEvent:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[textField resignFirstResponder];`
}
当你在背景中触摸任何地方时,这将使键盘消失。
杰里米的回答不太适合我,我想是因为我在一个选项卡视图中有一个导航堆栈,上面有一个模态对话框。我现在使用下面的,它是为我工作,但你的里程可能会有所不同。
// dismiss keyboard (mostly macro)
[[UIApplication sharedApplication].delegate dismissKeyboard]; // call this in your to app dismiss the keybaord
// --- dismiss keyboard (in indexAppDelegate.h) (mostly macro)
- (void)dismissKeyboard;
// --- dismiss keyboard (in indexAppDelegate.m) (mostly macro)
// do this from anywhere to dismiss the keybard
- (void)dismissKeyboard { // from: http://stackoverflow.com/questions/741185/easy-way-to-dismiss-keyboard
UITextField *tempTextField = [[UITextField alloc] initWithFrame:CGRectZero];
UIViewController *myRootViewController = <#viewController#>; // for simple apps (INPUT: viewController is whatever your root controller is called. Probably is a way to determine this progragrammatically)
UIViewController *uivc;
if (myRootViewController.navigationController != nil) { // for when there is a nav stack
uivc = myRootViewController.navigationController;
} else {
uivc = myRootViewController;
}
if (uivc.modalViewController != nil) { // for when there is something modal
uivc = uivc.modalViewController;
}
[uivc.view addSubview:tempTextField];
[tempTextField becomeFirstResponder];
[tempTextField resignFirstResponder];
[tempTextField removeFromSuperview];
[tempTextField release];
}
推荐文章
- Xcode构建失败“架构x86_64未定义的符号”
- 动态改变UILabel的字体大小
- registerForRemoteNotificationTypes: iOS 8.0及以上版本不支持
- 新的自动引用计数机制是如何工作的?
- 如何测试对象在Objective-C中的类?
- 是否有可能禁用浮动头在UITableView与UITableViewStylePlain?
- 从Cocoa应用程序执行一个终端命令
- Swift编译器错误:“框架模块内的非模块化头”
- 从父iOS访问容器视图控制器
- 自定义dealloc和ARC (Objective-C)
- 调整UITableView的大小以适应内容
- 在代码中为UIButton设置一个图像
- UICollectionView中的单元格间距
- 我如何在我的iOS应用程序中每n分钟得到一个后台位置更新?
- 如何使用UIVisualEffectView来模糊图像?