//
// ViewController.m
// 键盘通知加动画
//
// Created by rimi on 15/8/22.
// Copyright (c) 2015年 LiuCong. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()<UITextFieldDelegate>
@property(nonatomic, strong) UITextField *TextF;
@property(nonatomic, assign) NSInteger keyboardY;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//定义一个TextField
UITextField *TextF = [[UITextField alloc] init];
TextF.bounds = CGRectMake(0, 0, 200, 45);
TextF.backgroundColor = [UIColor colorWithRed:0.823 green:0.766 blue:1.000 alpha:1.000];
TextF.center = CGPointMake(CGRectGetMidX(self.view.bounds), 500);
[TextF setBorderStyle:UITextBorderStyleRoundedRect];
self.TextF = TextF;
//遵守UITextFieldDelegate
TextF.delegate = self;
[self.view addSubview:TextF];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}
//当用户按下return键或者按回车键,keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
//输入框编辑完成以后,将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}
- (void)keyboardWillShow:(NSNotification *)notification {
//获取键盘高度
NSDictionary* info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
//获取输入框的大小
CGRect frame = self.TextF.frame;
//计算输入框需要移动的距离
int offset = frame.origin.y + self.TextF.frame.size.height - (self.view.frame.size.height - kbSize.height);
//动画
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
//将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示
if(kbSize.height > 0)
self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations];
}
@end