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就是對應的父視圖,運用時請交換掉。
感激閱讀,希望能協助到大家,謝謝大家對本站的支持!
【IOS TextFiled與TextView 鍵盤的收起以及處置鍵盤遮擋】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!