键盘的显示很简单,点击一下UITextField就可以了。
[textUserName becomeFirstResponder];
键盘的关闭
打开键盘时,控件上升。点击背景,关闭键盘,控件下降。
在viewDidLoad里面创建一个键盘显示的通知,当系统监测到UIKeyboardWillShowNotification这个通知时,就会调用keyboardWillShow这个方法。同理创建一个键盘关闭的通知。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
然后将要上升的控件放到一个透明的UIView上面,命名为upDownView,然后写出对应的方法:
注:下降时,y坐标应该是20而不是0,因为下降后,view的顶部有导航条占位。
- (void)keyboardWillShow:(NSNotification *)aNotification {
[self uploadViewWithHight];
}
- (void)keyboardWillHide:(NSNotification *)aNotification {
[self downloadViewWithHight];
}
- (void)uploadViewWithHight {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
self.navigationController.navigationBarHidden = YES;
[self.upDownView setFrame:CGRectMake(self.upDownView.frame.origin.x, -110, self.upDownView.frame.size.width, self.upDownView.frame.size.height)];
[UIView commitAnimations];
}
- (void)downloadViewWithHight {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
self.navigationController.navigationBarHidden = NO;
[self.upDownView setFrame:CGRectMake(self.upDownView.frame.origin.x, 20, self.upDownView.frame.size.width, self.upDownView.frame.size.height)];
[UIView commitAnimations];
}
这个方法看似不错,但是运行起来的时候会发现一个问题,比如登录界面,当用户填写了用户名和密码之后,没有触摸背景,而是直接点击登录按钮,这时,点击登录按钮的时候,第一次点击是关闭键盘,第二次点击才能触发登录事件。为了解决这个问题,我将上面的代码进行了修改。
1、删除掉键盘关闭的通知
2、删掉keyboardWillHide方法
3、在ViewDidLoad中添加以下代码:注意tapGr.cancelsTouchesInView = NO这句代码挺重要,因为如果没有这一句,在view中的button等可能会无法触发TouchUpInside事件
UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
tapGr.cancelsTouchesInView = NO;
[self.upDownView addGestureRecognizer:tapGr];
4、创建方法:
- (void)viewTapped:(UITapGestureRecognizer *)tapGr {
[textUserName resignFirstResponder];
[textaPassword resignFirstResponder];
}
5、创建方法:(这个很重要,是实现我们目的的最关键)
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if (![textUserName isExclusiveTouch]) {
[textUserName resignFirstResponder];
self.navigationController.navigationBarHidden = NO;
[self.upDownView setFrame:CGRectMake(self.upDownView.frame.origin.x, 20, self.upDownView.frame.size.width, self.upDownView.frame.size.height)];
}
}
如果要让背景和控件一起上升,就去掉upDownView,直接把控件放在背景上。
如:[self.view addSubview:textUserName];
[self.view addSubview:textaPassword];
点击软键盘的return键,关闭键盘:
1、.h文件中创建一个方法:
- (IBAction)finishType:(UITextField *)sender;
2、将要关闭键盘的UITextField与这个方法用Did End On Exit相连。
3、在.m文件中:
- (IBAction)finishType:(UITextField *)sender {
[sender resignFirstResponder];
}
如果要用代码绑定,便可以调用UITextField的代理,其中一个方法:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
。。。
return YES;
}
此外还有一些博文写的很详细:
http://blog.csdn.net/xiaotanyu13/article/details/7711954