我有相当多的控件分散在我的表格中的许多表格单元格中,我想知道是否有一种更简单的方法来消除键盘,而不必循环遍历所有的控件并将它们全部辞职为第一响应器。我想问题是…我如何得到当前的第一个响应器的键盘?


当前回答

下面是我在代码中使用的代码。它像魔法一样有效!

在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键盘所占用的空间,为用户提供一种简单直观的方式来消除键盘是有意义的。

这是一个链接