类似做一个这样的搜索页面,有一个输入框,下面是搜索结果。
1、 点击输入框时,弹窗键盘;
2、输入完成,回车时,收起键盘;
3、点击输入框以外的区域,收起键盘;
4、左右滑动时,收起键盘;
5、上下滑动列表时,收起键盘;
- (void)viewDidLoad {
[super viewDidLoad];
// 其他代码
// 初始化输入框、列表、设置列表的委托
// 输入框是self.view的子孙元素
// 设置点击任何非文本框的地方都会隐藏键盘的手势
// 满足3
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
// 创建拖拽手势
// 满足4
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
[self.view addGestureRecognizer:panGestureRecognizer];
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
// 输入框回车
//满足2
[textField resignFirstResponder];
return YES;
}
#pragma mark - UIScrollViewDelegate
// 默认当前页面是列表的委托对象
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
// 上下滑动列表
// 满足5
[self dismissKeyboard];
}
// 执行隐藏键盘的操作
-(void)dismissKeyboard {
[self.view endEditing:YES];
}