有時候UI設(shè)計的輸入框太低,我們點擊輸入框彈出鍵盤可能會擋住輸入框,所以要讓視圖上移;
代碼如下:
#pragma mark - 鍵盤高度
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
}
/*!
*? @brief? 顯示鍵盤及設(shè)置高度
*
*? @param note 通知消息-需要設(shè)置的高度
*/
-(void)keyboardShow:(NSNotification *)note
{
CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat deltaY=keyBoardRect.size.height;
[UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
self.view.transform=CGAffineTransformMakeTranslation(0, -deltaY);
}];
}
/*!
*? @brief? 隱藏鍵盤及設(shè)置高度
*
*? @param note 通知消息-需要設(shè)置的高度
*/
-(void)keyboardHide:(NSNotification *)note
{
[UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
self.view.transform = CGAffineTransformIdentity;
}];
}
這段代碼表示點擊輸入框,整個self.view會根據(jù)鍵盤高度上移,然后隨著鍵盤消失,self.view回到原來位置(直接復(fù)制粘貼代碼即可)