通过通知监听键盘的状态来改变View的位置
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过通知监听键盘的状态来改变View的位置相关的知识,希望对你有一定的参考价值。
#import "ViewController.h"
@interface ViewController ()<UITextFieldDelegate>{
UIView * _mainView;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_mainView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 600)];
[self.view addSubview:_mainView];
_mainView.backgroundColor = [UIColor orangeColor];
// 新建一个UITextField,位置及背景颜色随意写的。
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(50, 100, 200, 40)];
textField.delegate = self;
textField.backgroundColor = [UIColor grayColor];
[self.view addSubview:textField]; // 自定义的view
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeContentViewPosition:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeContentViewPosition:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
// 根据键盘状态,调整_mainView的位置
- (void)changeContentViewPosition:(NSNotification *)notification{
NSDictionary *userInfo = [notification userInfo];
NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
// 得到键盘弹出后的键盘视图所在y坐标
CGFloat keyBoardEndY = value.CGRectValue.origin.y;
// 键盘弹出所用时间
NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
// 添加移动动画,使视图跟随键盘移动
[UIView animateWithDuration:duration.doubleValue animations:^{ [UIView setAnimationBeginsFromCurrentState:YES];
// 对View设置转场动画方向 枚举类型
[UIView setAnimationCurve:[curve intValue]];
_mainView.center = CGPointMake(_mainView.center.x, keyBoardEndY - 20 - _mainView.bounds.size.height/2.0); // keyBoardEndY的坐标包括了状态栏的高度,要减去
}];
}
-(void)dealloc{
//移除监听
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
@end
以上是关于通过通知监听键盘的状态来改变View的位置的主要内容,如果未能解决你的问题,请参考以下文章
ios开发之--通过通知监听textfield的输入状态,判断按钮的状态