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


当前回答

这里有很多过于复杂的答案,也许是因为这在iOS文档中不容易找到。约瑟夫在上面写着:

[[view window] endEditing:YES];

其他回答

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

在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];
}

最简单的方法是调用方法

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    if(![txtfld resignFirstResponder])
    {
        [txtfld resignFirstResponder];
    }
    else
    {

    }
    [super touchesBegan:touches withEvent:event];
}

你必须使用其中一种方法,

[self.view endEditing:YES];

or

[self.textField resignFirstResponder];

我最近需要使用的一个稍微健壮一点的方法:

- (void) dismissKeyboard {
    NSArray *windows = [UIApplication sharedApplication].windows;

    for(UIWindow *window in windows) [window endEditing:true];

    //  Or if you're only working with one UIWindow:

    [[UIApplication sharedApplication].keyWindow endEditing:true];
}

我发现其他一些“全局”方法不起作用(例如,UIWebView和WKWebView拒绝辞职)。

在你的视图控制器的头文件中添加<UITextFieldDelegate>到你的控制器接口的定义中,以便它符合UITextField委托协议…

@interface someViewController : UIViewController <UITextFieldDelegate>

... 在控制器的实现文件(.m)中添加以下方法,或者如果你已经有一个viewDidLoad方法,则在其中添加代码…

- (void)viewDidLoad
{
    // Do any additional setup after loading the view, typically from a nib.
    self.yourTextBox.delegate = self;
}

... 然后,链接你的文本框到你的实际文本字段

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField 
{
    if (theTextField == yourTextBox) {
        [theTextField resignFirstResponder];
    }
    return YES;
}