我有相当多的控件分散在我的表格中的许多表格单元格中,我想知道是否有一种更简单的方法来消除键盘,而不必循环遍历所有的控件并将它们全部辞职为第一响应器。我想问题是…我如何得到当前的第一个响应器的键盘?
当前回答
下面是我在代码中使用的代码。它像魔法一样有效!
在yourviewcontroller.h中添加:
@property(非atomic) UITapGestureRecognizer * taprenizer;
现在在.m文件中,将这个添加到你的ViewDidLoad函数中:
- (void)viewDidLoad {
//Keyboard stuff
tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapAnywhere:)];
tapRecognizer.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tapRecognizer];
}
同样,在.m文件中添加这个函数:
- (void)handleSingleTap:(UITapGestureRecognizer *) sender
{
[self.view endEditing:YES];
}
其他回答
你可能也需要覆盖UIViewController disablesautomatickeyboarddismiss来让它在某些情况下工作。如果你有UINavigationController,这可能必须在UINavigationController上完成。
最简单的方法是调用方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if(![txtfld resignFirstResponder])
{
[txtfld resignFirstResponder];
}
else
{
}
[super touchesBegan:touches withEvent:event];
}
从UITableView和UIScrollView中取消键盘的最好方法是:
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag
杰里米的回答不太适合我,我想是因为我在一个选项卡视图中有一个导航堆栈,上面有一个模态对话框。我现在使用下面的,它是为我工作,但你的里程可能会有所不同。
// 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];
}
关于如何在iOS中当用户触摸屏幕上UITextField或键盘之外的任何地方时取消键盘的快速提示。考虑到iOS键盘所占用的空间,为用户提供一种简单直观的方式来消除键盘是有意义的。
这是一个链接
推荐文章
- 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来模糊图像?