都在注釋里
//增加監(jiān)聽(tīng)佳励,當(dāng)鍵盤(pán)出現(xiàn)或改變時(shí)收出消息
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//增加監(jiān)聽(tīng)奔缠,當(dāng)鍵退出時(shí)收出消息
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
- (void)keyboardWillShow:(NSNotification *)aNotification{
NSDictionary *userInfo = [aNotification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
int height = keyboardRect.size.height;
// 設(shè)置動(dòng)畫(huà)的名字
[UIView beginAnimations:@"Animation" context:nil];
// 設(shè)置動(dòng)畫(huà)的間隔時(shí)間
[UIView setAnimationDuration:0.20];
// 使用當(dāng)前正在運(yùn)行的狀態(tài)開(kāi)始下一段動(dòng)畫(huà)
[UIView setAnimationBeginsFromCurrentState: YES];
// 獲取到textfiled 距底部距離
int textToTop = self.view.frame.size.height - self.numberTextFiled.frame.origin.y - self.numberTextFiled.frame.size.height;
if (textToTop > height) {
// 如果鍵盤(pán)高度小于textfiled距底部的距離 則不需要任何操作
}else{
// 當(dāng)textToTop 小于 height 時(shí)
// 獲取到鍵盤(pán)高度和控件底部距離的差值
int scrolldistance = height - textToTop;
// 移動(dòng)視圖y 差值距離
self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - scrolldistance, self.view.frame.size.width, self.view.frame.size.height);
}
//設(shè)置動(dòng)畫(huà)結(jié)束
[UIView commitAnimations];
}
//當(dāng)鍵退出時(shí)調(diào)用
- (void)keyboardWillHide:(NSNotification *)aNotification{
// 設(shè)置動(dòng)畫(huà)的名字
[UIView beginAnimations:@"Animation" context:nil];
// 設(shè)置動(dòng)畫(huà)的間隔時(shí)間
[UIView setAnimationDuration:0.20];
// 使用當(dāng)前正在運(yùn)行的狀態(tài)開(kāi)始下一段動(dòng)畫(huà)
[UIView setAnimationBeginsFromCurrentState: YES];
// 設(shè)置視圖移動(dòng)的位移至原來(lái)的y值
self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height);
//設(shè)置動(dòng)畫(huà)結(jié)束
[UIView commitAnimations];
}