IOS TextFiled与TextView 键盘的收起以及处理键盘遮挡
程序员文章站
2023-12-22 09:33:16
ios textfiled与textview 键盘的收起以及处理键盘遮挡
在ios开发中,uitextfiled和uitextview是很常见的两个控件,当...
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就是对应的父视图,使用时请替换掉。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!