鍵盤彈出後遮擋了textField是一種非常常見的情況,解決方案有很多種,我在這裡介紹其中一種方式。
這種方式能夠解決鍵盤彈出之後鍵盤高度發生變化(例如中文鍵盤,輸入字母之後最上面會多出一塊候選單詞的區域),textField或view的位置變化。
首先對controller添加消息監聽。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
notification的name是系統預設的值。該值常用的有以下四種:
UIKIT_EXTERN NSString *const UIKeyboardWillShowNotification;
UIKIT_EXTERN NSString *const UIKeyboardDidShowNotification;
UIKIT_EXTERN NSString *const UIKeyboardWillHideNotification;
UIKIT_EXTERN NSString *const UIKeyboardDidHideNotification;
分别代表了鍵盤将要顯示,顯示完成,将要隐藏,隐藏完成的四個狀态。
根據需要選擇你要處理的狀态,但如果對UIKeyboardWillShowNotification添加監聽,在處理view位置變化的時候可能會因為系統自帶的鍵盤動畫導緻失效。
接下來是消息的處理:
#pragma mark - Notification
- (void)keyboardDidShow:(NSNotification *)noti
{
NSDictionary *info = [noti userInfo];
NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyBoardSize = [aValue CGRectValue].size;
CGRect rect = _bottomBarV.frame;
rect.origin.y = self.view.frame.size.height - keyBoardSize.height - rect.size.height;
_bottomBarV.frame = rect;
}
- (void)keyboardWillHide:(NSNotification *)noti
{
CGRect rect = _bottomBarV.frame;
rect.origin.y = self.view.frame.size.height - rect.size.height;
_bottomBarV.frame = rect;
}
首先,這段代碼需要你根據需要自己做一些調整。我貼出來的這段代碼适用的場景是一個位于螢幕最下方的view(_bottemBarV)當鍵盤彈起時,位移到鍵盤最上方。
其次,在show消息進行中,取到了一個key值為UIKeyboardFrameEndUserInfoKey。
該值為系統預設:
UIKIT_EXTERN NSString *const UIKeyboardFrameBeginUserInfoKey NS_AVAILABLE_IOS(3_2); // NSValue of CGRect
UIKIT_EXTERN NSString *const UIKeyboardFrameEndUserInfoKey NS_AVAILABLE_IOS(3_2); // NSValue of CGRect
UIKIT_EXTERN NSString *const UIKeyboardAnimationDurationUserInfoKey NS_AVAILABLE_IOS(3_0); // NSNumber of double
UIKIT_EXTERN NSString *const UIKeyboardAnimationCurveUserInfoKey NS_AVAILABLE_IOS(3_0); // NSNumber of NSUInteger (UIViewAnimationCurve)
UIKeyboardFrameBeginUserInfoKey和UIKeyboardFrameEndUserInfoKey描述的是兩種不同的狀态,鍵盤大小要發生變化時,Begin代表的是變化之前的狀态,End代表的是變化之後的狀态,是以這個地方小心不要弄混。
這個場景中,我們希望的是鍵盤高度變化之後,view相應的做出變化,是以取的是End狀态。
代碼中的keyBoardSize即代表了鍵盤的寬,高。然後你就可以根據鍵盤的大小,改變你想改變的view位置了。