@SanMao
2015-08-05T16:32:41.000000Z
字数 1977
阅读 1469
知识补充
---利用通知的方法监听键盘位置的改变
代码:
#import "ViewController.h"@interface ViewController ()// 获得TextField属性@property (weak, nonatomic) IBOutlet UITextField *textField;// 获得TextField的底部间距属性@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpace;@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];// 利用通知,监听键盘的位置// 添加监听// [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];// [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];// 最常用的通知[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];}- (void)dealloc{[[NSNotificationCenter defaultCenter] removeObserver:self];}- (void)keyBoardWillChange:(NSNotification *)note{// 获取键盘的frameCGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];// 获得键盘的动画时间CGFloat time = [UIKeyboardAnimationDurationUserInfoKey doubleValue];// 修改textfield的底部约束(屏幕的高度 - 键盘的最后Y值)[UIView animateWithDuration:time animations:^{self.bottomSpace.constant = self.view.frame.size.height - frame.origin.y;[self.view layoutIfNeeded];}];}//- (void)keyBoardWillShow:(NSNotification *)note{//// // 取出键盘的frame// CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];// // 修改textField的底部约束//// CGFloat time = [UIKeyboardAnimationDurationUserInfoKey doubleValue];// [UIView animateWithDuration:time animations:^{// self.bottomSpace.constant = frame.size.height;// [self.view layoutIfNeeded];// }];////}////- (void)keyBoardWillHide:(NSNotification *)note{//// CGFloat time = [UIKeyboardAnimationDurationUserInfoKey doubleValue];// [UIView animateWithDuration:time animations:^{// self.bottomSpace.constant = 0;// [self.view layoutIfNeeded];// }];////}-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{// 点击屏幕的时候隐藏键盘// [self.textField resignFirstResponder];// [self.textField endEditing:YES];[self.view endEditing:YES];}@end