iOS 中用了autolayout遮擋鍵盤的處理
先說明我的情況:1.我是用了masonry 和iOS內建的autolayout結合的 簡單的登入問題
loginView是我的一個登入背景,,設定的置中,,當我點擊輸入的時候,,我會判斷鍵盤是否會遮擋我的loginView,如果不會遮擋,,我就不需要改變loginView的frame,,,在autolayout中,如果要擷取正確的frame的一定要在viewDidAppear 方法中,,總之是要在viewDidAppear方法以後才可以。
-(void)viewDidLoad{ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];}#pragma mark - Notification center- (void)keyboardWillShowNotification:(NSNotification *)notification { // 擷取鍵盤基本資料(動畫時間長度與鍵盤高度) NSDictionary *userInfo = [notification userInfo]; NSLog(@"log:%@",NSStringFromCGRect(self.loginView.frame)); NSLog(@"%@",userInfo); CGRect rect = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue]; CGFloat keyboardHeight = CGRectGetHeight(rect)-(CGRectGetHeight(self.view.frame)-self.loginView.frame.origin.y-CGRectGetHeight(self.loginView.frame)); CGFloat keyboardDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; //判斷視圖是否被鍵盤遮擋住了 if (keyboardHeight>0) { // 修改邊距約束 [self.loginView mas_updateConstraints:^(MASConstraintMaker *make) { make.centerY.mas_equalTo(self.view).offset(-keyboardHeight); }]; // 更新約束 [UIView animateWithDuration:keyboardDuration animations:^{ [self.view layoutIfNeeded]; }]; }}- (void)keyboardWillHideNotification:(NSNotification *)notification { // 獲得鍵盤動畫時間長度 NSDictionary *userInfo = [notification userInfo]; CGFloat keyboardDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; // 修改為以前的約束(距下邊距0) [self.loginView mas_updateConstraints:^(MASConstraintMaker *make) { make.center.mas_equalTo(self.view); }]; // 更新約束 [UIView animateWithDuration:keyboardDuration animations:^{ [self.view layoutIfNeeded]; }];}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; [self.view endEditing:YES];}- (void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];}