## iOS 中用了autolayout遮擋鍵盤的處理 ##

來源:互聯網
上載者:User
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];}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.