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