12th,September,2016
说在前面
键盘回收可以说是开发中蛮常见的一个功能,基本上有涉及到文本编辑就会有键盘的相应处理。那就总结下几种键盘回收吧
回收键盘
- (void)resignFirstResponder; // 回收键盘
问题写在前面
[诡异问题1] 在实现添加swipe手势时,设置direction为上下,或者左右可以识别,但是当direction为上下左右时只能识别到左右轻扫手势,无法识别到上下手势,不知道哪里出了问题?
Show me Code
touchesBegan
常见于点击UIView视图,回收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.inputTextView resignFirstResponder];
}
Delegate
使用UITextField时,当点击return按键时,回收键盘。
#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (self.outLoginType == OutLoginTypeNickName) {
// 进入Out
[self setOutNameAction:nil];
} else {
if (textField == self.outNameTF) {
// 下一步
[self.outPasswdTF becomeFirstResponder];
} else if (textField == self.outPasswdTF) {
[self setOutNameAction:nil];// 登录
}
}
return YES;
}
UITextView控件可在键盘输入的时候判断输入的是否为\n进行回收键盘。
#pragma mark UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if ([text isEqualToString:@"\n"]) {
[textView resignFirstResponder];
return NO;
}
}
NSNotificationCenter
- 直接在textView上添加手势
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEndShowKeyboard:) name:UIKeyboardDidShowNotification object:nil];
}
- (void)didEndShowKeyboard:(NSNotification *)notification {
self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
[self.inputTextView addGestureRecognizer:self.tap];
}
- (void)hideKeyboard {
[self.inputTextView removeGestureRecognizer:self.tap];
[self.inputTextView resignFirstResponder];
}
// 移除通知,防止循环引用
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- 常见透明view,在上面添加手势
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEndShowKeyboard:) name:UIKeyboardDidShowNotification object:nil];
}
- (void)didEndShowKeyboard:(NSNotification *)notification {
self.keyView = [[UIView alloc] initWithFrame:self.inputTextView.frame];
self.keyView.backgroundColor = [UIColor clearColor];
[self.inputTextView addSubview:self.keyView];
self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
[self.keyView addGestureRecognizer:self.tap];
}
- (void)hideKeyboard {
[self.keyView removeGestureRecognizer:self.tap];
[self.keyView removeFromSuperview];
[self.inputTextView resignFirstResponder];
}
// 移除通知,防止循环引用
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}