#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 利用通知监听键盘变化
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)keyboardChanged:(NSNotification *)n {
NSLog(@"%@", n);
// 字典和数组中不能保存基本类型(NSNumber)以及结构体(NSValue)
// 键盘rect
CGRect rect = [n.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
self.bottomConstraint.constant = [UIScreen mainScreen].bounds.size.height - rect.origin.y;
// 动画时长
NSTimeInterval duration = [n.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// 动画
[UIView animateWithDuration:duration animations:^{
// 更新布局
[self.view layoutIfNeeded];
}];
}
@end