标签:
#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
标签:
原文地址:http://www.cnblogs.com/flyter/p/5618622.html