#define SINGLE_NOTICE [NSNotificationCenter defaultCenter]
#import "ViewController.h"
@interface ViewController ()<UITextFieldDelegate> {
float _keyboardHeight; // 键盘高度
UITextField *_currentTF; // 当前正在编辑的输入框
}
@end
@implementation ViewController
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[SINGLE_NOTICE addObserver:self selector:@selector(keyBoardWillShown:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[SINGLE_NOTICE removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
for (NSInteger i = 0; i<2; i++) {
// 方便对比,创建两个输入框
UITextField *tf = [[UITextField alloc] init];
tf.frame = CGRectMake(50, 500-300*i, 200, 40);
tf.backgroundColor = [UIColor lightGrayColor];
tf.placeholder = @"input your info at this...";
tf.delegate = self;
tf.returnKeyType = UIReturnKeyDone;
[tf setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.view addSubview:tf];
}
}
#pragma mark - 通知方法
- (void)keyBoardWillShown:(NSNotification *)noti {
NSDictionary *info = [noti userInfo];
NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGRect keyboardRect = [value CGRectValue];
if (_keyboardHeight == 0.000000) {
_keyboardHeight = keyboardRect.size.height;
[self makeTFVisible];
}
// NSLog(@"keyHeight===%f",_keyboardHeight);
_keyboardHeight = keyboardRect.size.height;
}
- (void)makeTFVisible {
float textFieldUpHeight = _keyboardHeight - (self.view.frame.size.height - (_currentTF.frame.size.height+_currentTF.frame.origin.y));
if (textFieldUpHeight > 0) {
[UIView animateWithDuration:0.25 animations:^{
self.view.frame = CGRectMake(0, -textFieldUpHeight, self.view.frame.size.width, self.view.frame.size.height);
}];
}
}
#pragma mark - 输入框代理方法 -
- (void)textFieldDidBeginEditing:(UITextField *)textField {
_currentTF = textField;
if (_keyboardHeight != 0.000000) {
[self makeTFVisible];
}
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
[UIView animateWithDuration:0.25 animations:^{
self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField.returnKeyType == UIReturnKeyDone) {
[textField resignFirstResponder];
}
return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}