如果鍵盤彈出覆寫了原有的試圖,這種效果并不好,是以我們就要在鍵盤彈出的時候,監聽鍵盤的位置來改變我們一些試圖的位置,例如tableView清單等;在這裡推薦一個大牛ibireme寫的YYKeyboardManager,Git位址:https://github.com/ibireme/YYKeyboardManager;用CocoaPods導入:pod 'YYKeyboardManager' ,終端 pod install 就可以使用了。
開啟鍵盤監聽
頭檔案引用:#import "YYKeyboardManager.h"
[[YYKeyboardManager defaultManager] addObserver:self];
實作代理
<YYKeyboardObserver>
代理方法
- (void)keyboardChangedWithTransition:(YYKeyboardTransition)transition {
[UIView animateWithDuration:transition.animationDuration delay:0 options:transition.animationOption animations:^{
///用此方法擷取鍵盤的rect
CGRect kbFrame = [[YYKeyboardManager defaultManager] convertRect:transition.toFrame toView:self.view];
///從新計算view的位置并指派
CGRect textframe = _textField.frame;
textframe.size.width = kbFrame.size.width;
textframe.origin.y = kbFrame.origin.y - textframe.size.height;
_textField.frame = textframe;
} completion:^(BOOL finished) {
}];
}
移除監聽
别忘了在釋放處移除監聽
- (void)dealloc {
[[YYKeyboardManager defaultManager] removeObserver:self];
}
最後附上一個原Git上項目的效果圖: