布局图片:
// ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
/** 文本框底部约束*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpace;
/** 文本框*/
@property (weak, nonatomic) IBOutlet UITextField *textField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
/**
* 监听键盘的frame即将发生改变的时候调用
*/
- (void)keyboardWillChange:(NSNotification *)note
{
// 获得键盘的frame
CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 修改底部约束
self.bottomSpace.constant = self.view.frame.size.height - frame.origin.y;
// 执行动画
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// 约束动画,利用duration时间去更新约束
[UIView animateWithDuration:duration animations:^{
// 强制布局
[self.view layoutIfNeeded];
}];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
程序一启动效果图片:
点击文本框效果图片:
点击空白区域效果图片: