使用第三方鍵盤時,代理方法會被調用3次,可能會有bug,解決辦法如下。

define WeakObj(o) __weak typeof(o) weak##o = o;

@interface ViewController()@property(weak, nonatomic) IBOutlet NSLayoutConstraint * bottomCons;//textV距離屏幕底部的約束,默認設置為0

@end

  • (void) viewDidLoad { [super viewDidLoad];

    // 監(jiān)聽鍵盤 將要 彈出和隱藏
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardWillShowOrHide: ) name: UIKeyboardWillShowNotification object: nil];

    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardWillShowOrHide: ) name: UIKeyboardWillHideNotification object: nil];

}

/** 第三方鍵盤將要顯示時, 此方法會被調用 3次,鍵盤y坐標依次為0,226,292:
2016-08-04 14:50:40.810 YZInputViewDemo[883:260581] 0.000000
2016-08-04 14:50:40.976 YZInputViewDemo[883:260581] 226.000000
2016-08-04 14:50:41.001 YZInputViewDemo[883:260581] 292.000000
即將隱藏時,拿到的鍵盤高度是292,所以代碼中直接寫死為 0
*/

  • (void) keyboardWillShowOrHide: (NSNotification * ) note {

    //注意,字典里存放的都是對象,要把對象轉為CGRect結構體,使用CGRectValue方法。
    CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];

    WeakObj(self);
    NSLog(@"%f", keyboardFrame.size.height);

    warning: 修改底部視圖距離底部的間距,

    之前下面方法放在keyboardWillChangeFrame:方法中,導致第3次292時,_bottomCons.constant == 0不成立,于是_bottomCons.constant被重新賦值為0!這就是bug原因。解決辦法就是監(jiān)聽將要顯示和將要消失兩個通知!
    // _bottomCons.constant = (_bottomCons.constant == 0 ? endFrame.size.height :
    // 0);
    // 修改底部視圖距離底部的間距
    if ([note.name isEqualToString: @"UIKeyboardWillHideNotification"]) {
    _bottomCons.constant = 0;
    } else { // willShow
    _bottomCons.constant = keyboardFrame.size.height;
    }

    [UIView animateWithDuration: duration animations: ^{ [weakself.view layoutIfNeeded];
    }];
    }

@end

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容