点击键盘,控件上移的方式
2016-01-12 16:13
239 查看
点击键盘,被挡住的控件的上移,回收键盘,控件回到原处,要实现这个功能,共有两种方法
一:(通知中心,监听键盘的弹起和回收)
1.监听键盘的弹起
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
2.监听弹起的时候的触发方法,用UIView的动画效果实现
// 键盘弹起的时候触发方法 - (void)keyBoardWillAppear:(NSNotification *)notification{ NSLog(@"键盘弹起了"); // 找到键盘的尺寸 CGRect rect = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; #warning 整体打印结构体的方法 NSLog(@"%@", NSStringFromCGRect(rect)); #warning 用动画效果让改变view的frame // 用UIView的动画,让视图随键盘向上平移 [UIView animateWithDuration:0.2 animations:^{ self.myView.frame = CGRectMake(100, 600 - rect.size.height, 200, 50); }]; }
3.监听键盘的回收
// 监听键盘的回收 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
4.键盘回收的时候实现的方法
(1)点击空白回收键盘
// 点击空白处回收键盘 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ [super touchesBegan:touches withEvent:event]; [self.textField resignFirstResponder]; }
(2)控件回到原处(view的动画效果, 可以再点击空白处回收键盘里实现,注意时间需要改成0.2)
// 让view回到原来的位置 - (void)keyBoardWillHidden:(NSNotification *)notification{ // 也可以在touch里写(在touch的方法里写,时间需要注意) [UIView animateWithDuration:2 animations:^{ self.myView.frame = CGRectMake(100, 600, 200, 50); }]; }
二:textField的协议方法
// 监控当前的状态 - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{ NSLog(@"编辑开始"); CGFloat height = textField.center.y - HEIGHT / 2; if (height > 0) { self.view.center = CGPointMake(self.view.center.x, HEIGHT / 2 - height); } return YES; } // 结束编辑 - (BOOL)textFieldShouldEndEditing:(UITextField *)textField{ CGFloat heigth = textField.center.y - HEIGHT / 2; if (heigth > 0) { self.view.center = CGPointMake(self.view.center.x, self.view.center.y + heigth); } return YES; }
相关文章推荐
- mongodb的lbs功能
- TortoiseSVN中Branching和Merging实践
- cocos2d-x 3.0 使用最新物理引擎的一个源代码实例
- oracle 开发 第06章 子查询
- windows server 2008服务器 做raid0
- 单元测试:前端代码测试 3
- 单元测试:前端代码测试 2
- 单元测试:前端代码测试 1
- Sqoop操作实践
- Jackson使用(三)
- Android知识点小积累系列---代码中从drawable下的图片转换为bitmap
- 深入浅出JMS(四)--Spring和ActiveMQ整合的完整实例
- Mac OS X中正确添加环境变量的方法
- windows 驱动验证数字证书
- 算法设计之DP
- 数据结构之图的的深度与广度优先遍历
- Sqoop操作实践
- python
- 七彩智能组卷软件系统、
- 《802.11无线网络权威指南》摘录