IOS TextFiled與TextView 鍵盤的收起以及處理鍵盤遮擋
在iOS開發中,UITextFiled和UITextView是很常見的兩個控件,當我們設置好這兩個控件後,點擊文字輸入區域,系統會自動彈出鍵盤,但是如何收起鍵盤、點擊哪裡收起鍵盤,以及在iPhone4中鍵盤彈出後遮擋輸入框怎麼辦呢?
這篇文章將帶領大家解決:
1》點擊其他空白區域收起鍵盤
2》點擊鍵盤右下角的鍵收起鍵盤
3》處理鍵盤遮擋問題
一,點擊其他空白區域收起鍵盤
- (void)viewDidLoad { [super viewDidLoad]; [self setUpForDismissKeyboard]; }
#pragma mark - 回收任何空白區域鍵盤事件 - (void)setUpForDismissKeyboard { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; UITapGestureRecognizer *singleTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAnywhereToDismissKeyboard:)]; NSOperationQueue *mainQuene =[NSOperationQueue mainQueue]; [nc addObserverForName:UIKeyboardWillShowNotification object:nil queue:mainQuene usingBlock:^(NSNotification *note){ [self.view addGestureRecognizer:singleTapGR]; }]; [nc addObserverForName:UIKeyboardWillHideNotification object:nil queue:mainQuene usingBlock:^(NSNotification *note){ [self.view removeGestureRecognizer:singleTapGR]; }]; } - (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer { //此method會將self.view裡所有的subview的first responder都resign掉 [self.view endEditing:YES]; }
二,點擊鍵盤右下角的鍵收起鍵盤
#pragma mark - TextView 代理方法 -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if ([text isEqualToString:@"\n"]) { [self.workLogTextView resignFirstResponder]; return NO; } return YES; }
注意:需要遵守textView/textFiled的代理。改代碼是textView代理方法,若實際用到的是textFiled,只需調用textFiled的該類方法即可。
三,處理鍵盤遮擋問題
#pragma mark 鍵盤遮擋 - (BOOL)textViewShouldBeginEditing:(UITextView *)textView { if (self.userInfo.isPhone4) { CGFloat offset_y = 0.f; if (textView.tag == CALL_CONTENT_TEXTFIRLD) { offset_y = 100.f; } CGPoint point = self.BackScrollView.contentOffset; point = CGPointMake(point.x, offset_y); [UIView animateWithDuration:0.25 animations:^{ self.BackScrollView.contentOffset = point; }]; } return YES; } - (BOOL)textViewShouldEndEditing:(UITextView *)textView{ if (self.userInfo.isPhone4) { CGFloat offset_y = 0.f; if (textView.tag == CALL_CONTENT_TEXTFIRLD) { offset_y = 100.f; } CGPoint point = self.BackScrollView.contentOffset; point = CGPointMake(point.x, 0); [UIView animateWithDuration:0.25 animations:^{ self.BackScrollView.contentOffset = point; }]; } return YES; }
注意:需要遵守 UIScrollViewDelegate 和 textView/textFiled的代理。需要該頁面的父視圖是UIScrollView,才能保證彈出鍵盤時頁面向上移動,收起鍵盤時頁面向下移動。代碼中的self.BackScrollView就是對應的父視圖,使用時請替換掉。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!