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


当前回答

杰里米的回答不太适合我,我想是因为我在一个选项卡视图中有一个导航堆栈,上面有一个模态对话框。我现在使用下面的,它是为我工作,但你的里程可能会有所不同。

 // 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];

}

其他回答

你应该发送enditing:到工作窗口作为UIView的子类

[[UIApplication sharedApplication].windows.firstObject endEditing:NO];

是的,终止是最好的选择。从iOW 7.0开始,UIScrollView有一个很酷的功能,可以在与滚动视图交互时取消键盘。为此,你可以设置UIScrollView的keyboardDismissMode属性。

设置键盘解散模式为:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag

它几乎没有其他类型。看看这个苹果文档。

更好的方法是让某些东西“窃取”第一响应者的地位。

因为UIApplication是UIResponder的子类,你可以尝试:

[[UIApplication sharedApplication] becomeFirstResponder]
[[UIApplication sharedApplication] resignFirstResponder]

如果做不到这一点,创建一个新的UITextField与一个零大小的框架,将它添加到一个视图的某处,并做一些类似的事情(成为后跟辞职)。

添加一个点击手势识别器到您的视图。并定义为ibaction

你的。m文件就像

    - (IBAction)hideKeyboardGesture:(id)sender {
    NSArray *windows = [UIApplication sharedApplication].windows;
    for(UIWindow *window in windows) [window endEditing:true];
    [[UIApplication sharedApplication].keyWindow endEditing:true];
}

这对我很有效

在你的视图控制器的头文件中添加<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;
}