在用戶進(jìn)行輸入時,彈出的鍵盤窗口有時會遮擋輸入框,為了解決這一問題,需要在鍵盤彈出時,將用戶界面向上平移,并在鍵盤消失時恢復(fù)原狀態(tài)。如果在每個ViewController里處理這個問題,會造成大量的重復(fù)代碼,并且不利于維護(hù)。所以我們嘗試讓所有的ViewController繼承自同一個父類,并在父類中統(tǒng)一處理。
首先重寫ViewDidload注冊鍵盤彈出和消失的事件
- (void)viewDidLoad
{
[super viewDidLoad];
[self initKeyboardNotifacation];
}
- (void)initKeyboardNotifacation
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
實(shí)現(xiàn)彈出鍵盤事件
- (void)keyboardWillShow:(NSNotification *)notification
{
if (!self.view.superview) {
return;
}
//1
UIWindow *keyWindow = nil;
NSArray *windowsArray = [[UIApplication sharedApplication] windows];
keyWindow = windowsArray[0];
//2
NSValue *rectValue = [notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGFloat keyboardHeight = [rectValue CGRectValue].size.height;
//3
UIView *firstResponder = [self.view findFirstResponder];
CGRect actionframe = [firstResponder.superview convertRect:firstResponder.frame toView:keyWindow];
//4
_space = 0.0f;
_space = actionframe.origin.y + actionframe.size.height + keyboardHeight - keyWindow.frame.size.height;
//5
if (_space > 0.0f) {
[UIView animateWithDuration:0.3 animations:^{
CGRect frame = self.view.frame;
frame.origin.y -= _space;
[self.view setFrame:frame];
}];
}else{
_space = 0.0f;
}
}
1、獲取當(dāng)前的keywindow
2、獲取鍵盤彈出高度
3、獲取當(dāng)前的第一響應(yīng)者,即用戶點(diǎn)擊的控件,并計算View在窗口中的位置
這里使用了UIView的分類方法
- (UIView *)findFirstResponder
{
if (self.isFirstResponder) {
return self;
}
for (UIView *subView in self.subviews) {
UIView *firstResponder = [subView findFirstResponder];
if (firstResponder) {
return firstResponder;
}
}
return nil;
}
//這個方法也可以獲取,但是審核會被拒,慎用。
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView *firstResponder = [keyWindow performSelector:@selector(firstResponder)];
文/舒耀(簡書作者)原文鏈接:http://m.itdecent.cn/p/f58e1036de4e著作權(quán)歸作者所有,轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),并標(biāo)注“簡書作者”。
4、計算需要上移的距離
5、判斷是否需要移動界面,不需要則初始化_space
鍵盤消失
- (void)keyboardWillHide:(NSNotification *)notification
{
[UIView animateWithDuration:0.3 animations:^{
CGRect frame = self.view.frame;
frame.origin.y += _space;
[self.view setFrame:frame];
}];
}
如果點(diǎn)擊的界面換成TextView這種富文本的控件,就不能簡單的平移控件的高度了,可以嘗試動態(tài)的獲取內(nèi)容的高度,在ChangeText里面進(jìn)行處理
如果發(fā)現(xiàn)代碼中存在任何問題,請在留言中進(jìn)行糾正