输入框跟随键盘弹出的效果
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *suspendView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UITapGestureRecognizer *tapgest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackAction)];
[self.view addGestureRecognizer:tapgest];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewWillAppear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)tapBackAction {
[self.view endEditing:YES];
}
- (void)keyBoardWillShow:(NSNotification *) note {
NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
CGRect keyBoardBounds = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat keyBoardHeight = keyBoardBounds.size.height;
CGFloat animationTime = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
void (^animation)(void) = ^void(void) {
self.suspendView.transform = CGAffineTransformMakeTranslation(0, - keyBoardHeight);
};
if (animationTime > 0) {
[UIView animateWithDuration:animationTime animations:animation];
} else {
animation();
}
}
- (void)keyBoardWillHide:(NSNotification *) note {
NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
CGFloat animationTime = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
void (^animation)(void) = ^void(void) {
self.suspendView.transform = CGAffineTransformIdentity;
};
if (animationTime > 0) {
[UIView animateWithDuration:animationTime animations:animation];
} else {
animation();
}
}
@end