我有相当多的控件分散在我的表格中的许多表格单元格中,我想知道是否有一种更简单的方法来消除键盘,而不必循环遍历所有的控件并将它们全部辞职为第一响应器。我想问题是…我如何得到当前的第一个响应器的键盘?
当前回答
用swift:
self.view.endEditing(true)
其他回答
在swift 3中,您可以执行以下操作
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
杰里米的回答不太适合我,我想是因为我在一个选项卡视图中有一个导航堆栈,上面有一个模态对话框。我现在使用下面的,它是为我工作,但你的里程可能会有所不同。
// 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];
}
您可以使用[view ended:YES]强制当前正在编辑的视图放弃其第一响应器状态。这样就隐藏了键盘。
与-[UIResponder resignFirstResponder]不同,-[UIView enditing:]将通过子视图搜索当前的第一响应器。所以你可以把它发送到顶层视图(比如self)。UIViewController中的view)它会做正确的事情。
(这个答案之前包含了几个其他的解决方案,它们也可以工作,但比必要的更复杂。为了避免混淆,我把它们去掉了。)
要在键盘弹出后关闭键盘,有两种情况,
当UITextField在UIScrollView中 当UITextField在UIScrollView之外时
2.当UITextField在UIScrollView之外时 重写UIViewController子类中的方法
你还必须为所有UITextView添加委托
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
在滚动视图中,点击外部不会触发任何事件,所以在这种情况下使用点击手势识别器, 拖拽滚动视图的UITapGesture并为其创建IBAction。
要创建一个IBAction,按ctrl+单击UITapGesture并将其拖到视图控制器的.h文件中。
这里我将tappedEvent命名为我的动作名
- (IBAction)tappedEvent:(id)sender {
[self.view endEditing:YES]; }
以上所提供的信息来自以下链接,如果您不理解以上数据,请参阅更多信息或与我联系。
http://samwize.com/2014/03/27/dismiss-keyboard-when-tap-outside-a-uitextfield-slash-uitextview/
这里有很多过于复杂的答案,也许是因为这在iOS文档中不容易找到。约瑟夫在上面写着:
[[view window] endEditing:YES];
推荐文章
- 为什么ARC仍然需要@autoreleasepool ?
- 首先添加一个UIView,甚至是导航栏
- 我如何改变UIButton标题颜色?
- 如何从UIImage (Cocoa Touch)或CGImage (Core Graphics)获取像素数据?
- 在Swift中如何调用GCD主线程上的参数方法?
- iOS -构建失败,CocoaPods无法找到头文件
- Xcode 4挂在“附加到(应用程序名称)”
- 以编程方式创建segue
- 在Objective-C中@synchronized如何锁定/解锁?
- Xcode构建失败“架构x86_64未定义的符号”
- 动态改变UILabel的字体大小
- registerForRemoteNotificationTypes: iOS 8.0及以上版本不支持
- 新的自动引用计数机制是如何工作的?
- 如何测试对象在Objective-C中的类?
- 是否有可能禁用浮动头在UITableView与UITableViewStylePlain?