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


当前回答

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

设置键盘解散模式为:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag

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

其他回答

我讨厌没有“全局”的方法在不使用私有API调用的情况下以编程方式取消键盘。我经常需要在不知道哪个对象是第一个响应器的情况下以编程方式关闭键盘。我使用Objective-C运行时API检查self,枚举它的所有属性,取出那些类型为UITextField的属性,并将resignFirstResponder消息发送给它们。

做这件事不应该这么难…

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

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

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

@Nicholas Riley &@Kendall Helmstetter Geln & @cannyboy:

绝对的辉煌!

谢谢你!

考虑到你和其他人在这篇文章中的建议,以下是我所做的:

使用时的样子:

[[self appDelegate]解聘键盘];(注意:我添加了appDelegate作为NSObject的补充,所以我可以在任何地方使用任何东西)

引擎盖下的样子:

- (void)dismissKeyboard 
{
    UITextField *tempTextField = [[[UITextField alloc] initWithFrame:CGRectZero] autorelease];
    tempTextField.enabled = NO;
    [myRootViewController.view addSubview:tempTextField];
    [tempTextField becomeFirstResponder];
    [tempTextField resignFirstResponder];
    [tempTextField removeFromSuperview];
}

EDIT

修正我的回答包括tempTextField。enabled = NO;。禁用文本字段将阻止UIKeyboardWillShowNotification和UIKeyboardWillHideNotification键盘通知发送,如果你在整个应用程序中依赖这些通知。

更新

我找到了另一种简单的方法

简单地声明一个属性:-

@property( strong , nonatomic) UITextfield *currentTextfield;

和一个Tap Gesture Gecognizer:-

@property (strong , nonatomic) UITapGestureRecognizer *resignTextField;

在ViewDidLoad

_currentTextfield=[[UITextField alloc]init];
_resignTextField=[[UITapGestureRecognizer alloc]initWithTarget:@selector(tapMethod:)];

[self.view addGestureRecognizer:_resignTextField];

实现文本字段委托方法didBeginEditing

 -(void)textFieldDidBeginEditing:(UITextField *)textField{


      _currentTextfield=textField;

    }

实现点击手势方法(_resignTextField)

 -(void)tapMethod:(UITapGestureRecognizer *)Gesture{

     [_currentTextfield resignFirstResponder];

 }