我有相当多的控件分散在我的表格中的许多表格单元格中,我想知道是否有一种更简单的方法来消除键盘,而不必循环遍历所有的控件并将它们全部辞职为第一响应器。我想问题是…我如何得到当前的第一个响应器的键盘?
当前回答
@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];
}
下面是我在代码中使用的代码。它像魔法一样有效!
在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];
}
这不是很漂亮,但是当我不知道responder是什么时,我辞去firstResponder的方式:
创建一个UITextField,无论是在IB或编程。把它隐藏起来。如果你是用IB写的,就把它链接到你的代码上。 然后,当你想要解散键盘时,你将响应器切换到不可见的文本字段,并立即辞职:
[self.invisibleField becomeFirstResponder];
[self.invisibleField resignFirstResponder];
Try:
[self.view endEditing:YES];
你应该发送enditing:到工作窗口作为UIView的子类
[[UIApplication sharedApplication].windows.firstObject endEditing:NO];
推荐文章
- iPhone上UIView和UILabels的渐变
- 在实现API时,我如何避免在块中捕获自我?
- 从另一个应用程序打开设置应用程序
- 使用NSURLSession发送POST请求
- 自动布局- UIButton的固有大小不包括标题插入
- 如何更改导航栏上“后退”按钮的标题
- 有没有办法从UITableView中移除分隔线?
- 如何在Objective-C中声明类级属性?
- 在Objective-C中@property保留,赋值,复制,非原子
- 我如何在NSAttributedString中创建一个可点击的链接?
- 停止UIWebView垂直“弹跳”?
- 对未渲染的视图进行快照,结果是一个空快照
- 开始使用instancetype而不是id是否有益?
- 改变UISegmentedControl的字体大小
- 我可以强制UITableView隐藏分隔符之间的空单元格吗?