方式1. 使用當雙擊輸入的時候彈出鍵盤同時,使用手勢和通知監聽鍵盤的方法實現
程式碼如下:
1. 監聽鍵盤通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addTap) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyDismiss) name:UIKeyboardWillHideNotification object:nil];
2. 彈出鍵盤中新增方法
- (void)addTap {
_tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resign)];
[self.view addGestureRecognizer:_tap];//self.view 可以視情況改動
}
3. 手勢的事件
#pragma mark - 點選手勢的事件方法
- (void)resign {
[self.view endEditing:YES];
}
4. 鍵盤消失的方法
- (void)keyDismiss {
[self.view removeGestureRecognizer:_tap];
}
方式2: 使用textView 的代理方法
#pragma mark - textView 的代理方法
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if ([text isEqualToString:@"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}