iOS实现textfield随键盘移动
来源:互联网 发布:我知这世界露水日文 编辑:程序博客网 时间:2024/05/20 18:55
在iOS中,点击textfield控件会弹出系统键盘,如果键盘位置在下方,那么会出现该控件被键盘遮挡的情况,这时候就需要让textfield的位置随着键盘弹出而变换。研究了一下关键代码如下。
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyBoardDidShow:)name:UIKeyboardDidShowNotificationobject:nil];
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyBoardDidHide:)name:UIKeyboardDidHideNotificationobject:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardDidShowNotificationobject:nil];
[[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardDidHideNotificationobject:nil];
}
- (void)keyBoardDidShow:(NSNotification *)notif {
NSLog(@"===keyboar showed====");
if (keyboardDidShow) return;// get keyboard size
NSDictionary *info = [notif userInfo];
NSValue *aValue = [infoobjectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;// reset scrollview frame
CGRect viewFrame = self.scrollView.frame;
viewFrame.size.height -= keyboardSize.height;
self.scrollView.frame = viewFrame;// scroll to current textfiled
CGRect textfieldRect = [self.textfieldframe];
[self.scrollView scrollRectToVisible:textfieldRect animated:YES];
keyboardDidShow = YES;
}
- (void)keyBoardDidHide:(NSNotification *)notif {
NSLog(@"====keyboard hidden====");
NSDictionary *info = [notif userInfo];
NSValue *aValue = [infoobjectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
CGRect viewFrame = self.scrollView.frame;
viewFrame.size.height += keyboardSize.height;
self.scrollView.frame = viewFrame;
if (!keyboardDidShow) {return;}
keyboardDidShow = NO;
}
对代码的解释:
UIKeyboardDidShowNotification,UIKeyboardDidHideNotification分别是键盘出现和键盘消失的通知。将ScrollView滚动到textfield控件,通过scrollRectToVisible:animated:来实现,其中scrollRectToVisible参数用于指定滚动到一个矩形区域,文档中解释为:Scrolls a specific area of the content so that it is visible in the receiver.这个矩形区域是CGRect结构体。每个视图的frame方法可以获得CGRrect结构体数据。
- iOS实现textfield随键盘移动
- IOS TextField伴随键盘移动
- cocos TextField + ios键盘 状态监听 移动view
- iOS textField 回收键盘
- IOS 键盘遮住了TextField
- textfield随键盘动
- iOS TextField 弹出键盘时实现view整体上移下移:防止弹出键盘遮挡输入框
- textField文本框随键盘上移
- IOS开发 textField 键盘遮挡问题
- IOS中TextField点击取消键盘
- ios 键盘遮盖TextField的解决方法
- ios TextField 不被键盘遮住
- iOS模拟器,点击textfield弹出键盘
- iOS开发 textField 键盘遮挡问题
- IOS中textField如何关闭键盘
- iOS开发TextField根据键盘自适应位置
- iOS TextField收取键盘的方法
- ios-关闭键盘于打开键盘的方式之textField
- Problem C
- js方法调方法写法
- Ubunt 系统安装
- 【项目管理】 使用IntelliJ IDEA 将项目发布(提交)到GitLab
- http://elf8848.iteye.com/blog/875830/
- iOS实现textfield随键盘移动
- Java反编译插件 Jad和JD-Core
- Qt中配置Winpcap
- Codeforces 652D Nested Segments 【树状数组 + 离散化】
- ORACLE 日期加减操作
- selenium-python安装
- C语言中的static
- Swith-实现单例的四种方法
- 国企,外企,还是民企?