李洪强iOS开发之- 点击屏幕遮挡键盘
实现的效果:
01 - 给当前的view添加点击事件,使点击屏幕的时候,让键盘退出
/**
* 点击屏幕 隐藏键盘
*
* @param tap
*/
-(void)keyboardHide:(UITapGestureRecognizer*)tap
{
[self.view endEditing:YES];
}
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
//设置成NO表示当前控件响应后会传播到其他控件上,默认为YES。
tapGestureRecognizer.cancelsTouchesInView = NO;
//将触摸事件添加到当前view
[self.view addGestureRecognizer:tapGestureRecognizer];
#import "CFShoppingCartViewController.h"
02 - 实现点击输入框 的时候,让当前的view整体上移,目的是不遮盖当前的输入框
03 - 实现textview的代理
#pragma mark --- 实现UITextView的代理---
-(void)textViewDidChange:(UITextView *)textView
{
_textView11.text = textView.text;
if (textView.text.length == 0) {
_label11.text = @"有什么需要补充的";
}else{
_label11.text = @"";
}
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
_label11.text = @"";
// [self.label1 removeFromSuperview];
return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
_label11.text = @"";
return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[UIView animateWithDuration:0.8 animations:^{
[self.view endEditing:YES];
}];
}
03 - 键盘的通知
#pragma mark — 键盘遮挡
-(void)createNotifiticationCenter
{
//创建通知中心
NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
//键盘弹出
[center addObserver:self selector:@selector(receivesKeyBordShowNotification:) name:UIKeyboardWillShowNotification object:nil];
//监听键盘收回时发送的通知
[center addObserver:self selector:@selector(receivesKeyBordHiddenNotification:) name:UIKeyboardWillHideNotification object:nil];
}
-(void)receivesKeyBordShowNotification:(NSNotification *)noti
{
//取出键盘的弹起时间
NSTimeInterval time = [[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]doubleValue];
//在键盘的这段时间内将界面上的控件上移
//使用动画
[UIView animateWithDuration:time delay:0 options:0 animations:^{
//将界面整体上移
CGRect boubds = self.view.bounds;
boubds.origin.y = 170;
self.view.bounds = boubds;
} completion:^(BOOL finished) {
}];
}
-(void)receivesKeyBordHiddenNotification:(NSNotification *)notifi
{
//从通知信息体取出键盘收回的时间
NSTimeInterval time = [[notifi.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]doubleValue];
//用动画将界面下移
[UIView animateWithDuration:time delay:0 options:0 animations:^{
CGRect bounds = self.view.bounds;
bounds.origin.y = 0;
self.view.bounds = bounds;
} completion:^(BOOL finished) {
}];
}