// AppDelegate.m
// NotificationText
//
// Created by 杜重庆 on 15/11/4.
// Copyright © 2015年 杜重庆. All rights reserved.
//
#import "AppDelegate.h"
#import "ViewController.h"
@interface AppDelegate ()
self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[ViewController new]];
#import "ViewController.h"
#define kWIDTH [UIScreen mainScreen].bounds.size.width
#define kHEIGHT [UIScreen mainScreen].bounds.size.height
@interface ViewController ()
@property(nonatomic, strong)UITextField *textField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.[
self.view.backgroundColor = [UIColor greenColor];
self.title = @"NotificationText";
self.navigationController.navigationBar.barTintColor = [UIColor redColor];
self.navigationController.navigationBar.translucent = NO;
NSDictionary *dic = @{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:22]};
self.navigationController.navigationBar.titleTextAttributes = dic;
/**
添加通知/观察者
*/
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeFrame:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeFrameTow:) name:UIKeyboardWillHideNotification object:nil];
/**
创建UITextField
*/
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(50, kHEIGHT - 164, kWIDTH - 100, 35)];
/**
设置键盘样式为圆角
*/
self.textField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:self.textField];
}
//注销观察者
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
/**
此时的动画是:点击textField输入框会向上做动画,并且距离上边导航条的距离是100.
*/
- (void)changeFrame:(NSNotification *)sender {
CGRect frame = self.textField.frame;
frame.origin.y = 100;
[UIView animateWithDuration:2 animations:^{
self.textField.frame = frame;
}];
}
/**
此时的动画是:点击空白区域键盘回收,输入框会回到原来的位置,(距离最下边的距离是 kHEIGHT - 164)
*/
- (void)changeFrameTow:(NSNotification *)sender {
CGRect frame = self.textField.frame;
<pre name="code" class="objc"> frame.origin.y = kHEIGHT - 164;
<pre name="code" class="objc"> [UIView animateWithDuration:2 animations:^{
self.textField.frame = frame;
}];
}
//键盘回收
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.textField resignFirstResponder];
}