IOS TextFiled与TextView 键盘的收起以及处理键盘遮挡
IOSTextFiled与TextView键盘的收起以及处理键盘遮挡
在iOS开发中,UITextFiled和UITextView是很常见的两个控件,当我们设置好这两个控件后,点击文字输入区域,系统会自动弹出键盘,但是如何收起键盘、点击哪里收起键盘,以及在iPhone4中键盘弹出后遮挡输入框怎么办呢?
这篇文章将带领大家解决:
1》点击其他空白区域收起键盘
2》点击键盘右下角的键收起键盘
3》处理键盘遮挡问题
一,点击其他空白区域收起键盘
-(void)viewDidLoad{
[superviewDidLoad];
[selfsetUpForDismissKeyboard];
}
#pragmamark-回收任何空白区域键盘事件
-(void)setUpForDismissKeyboard{
NSNotificationCenter*nc=[NSNotificationCenterdefaultCenter];
UITapGestureRecognizer*singleTapGR=
[[UITapGestureRecognizeralloc]initWithTarget:self
action:@selector(tapAnywhereToDismissKeyboard:)];
NSOperationQueue*mainQuene=[NSOperationQueuemainQueue];
[ncaddObserverForName:UIKeyboardWillShowNotification
object:nil
queue:mainQuene
usingBlock:^(NSNotification*note){
[self.viewaddGestureRecognizer:singleTapGR];
}];
[ncaddObserverForName:UIKeyboardWillHideNotification
object:nil
queue:mainQuene
usingBlock:^(NSNotification*note){
[self.viewremoveGestureRecognizer:singleTapGR];
}];
}
-(void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer*)gestureRecognizer{
//此method会将self.view里所有的subview的firstresponder都resign掉
[self.viewendEditing:YES];
}
二,点击键盘右下角的键收起键盘
#pragmamark-TextView代理方法
-(BOOL)textView:(UITextView*)textViewshouldChangeTextInRange:(NSRange)rangereplacementText:(NSString*)text
{
if([textisEqualToString:@"\n"]){
[self.workLogTextViewresignFirstResponder];
returnNO;
}
returnYES;
}
注意:需要遵守textView/textFiled的代理。改代码是textView代理方法,若实际用到的是textFiled,只需调用textFiled的该类方法即可。
三,处理键盘遮挡问题
#pragmamark键盘遮挡
-(BOOL)textViewShouldBeginEditing:(UITextView*)textView{
if(self.userInfo.isPhone4){
CGFloatoffset_y=0.f;
if(textView.tag==CALL_CONTENT_TEXTFIRLD){
offset_y=100.f;
}
CGPointpoint=self.BackScrollView.contentOffset;
point=CGPointMake(point.x,offset_y);
[UIViewanimateWithDuration:0.25animations:^{
self.BackScrollView.contentOffset=point;
}];
}
returnYES;
}
-(BOOL)textViewShouldEndEditing:(UITextView*)textView{
if(self.userInfo.isPhone4){
CGFloatoffset_y=0.f;
if(textView.tag==CALL_CONTENT_TEXTFIRLD){
offset_y=100.f;
}
CGPointpoint=self.BackScrollView.contentOffset;
point=CGPointMake(point.x,0);
[UIViewanimateWithDuration:0.25animations:^{
self.BackScrollView.contentOffset=point;
}];
}
returnYES;
}
注意:需要遵守UIScrollViewDelegate和textView/textFiled的代理。需要该页面的父视图是UIScrollView,才能保证弹出键盘时页面向上移动,收起键盘时页面向下移动。代码中的self.BackScrollView就是对应的父视图,使用时请替换掉。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!