在學習iOS開發的過程中總是遇見鍵盤出現時,遮蓋了輸出口UITextField,無法看到用戶自己輸出的內容。這時就需要對當前視圖做出相應的上移,當輸出結束時點擊屏幕的任意地方,使鍵盤彈回去。
第一種方法是在UITextField開始編輯前和編輯后調用的方法里添加移動視圖的方法;第二種方法是新創建一個視圖移動的方法,兩次都調用,并判斷是否做出相應移動。
把兩種方法貼出來,都需要在.h文件中添加UITextFieldDelegate協議,還需要設置委托,此處略過
//***更改frame的值***//
//在UITextField 編輯之前調用方法
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
//設置動畫的名字
[UIView beginAnimations:@"Animation"context:nil];
//設置動畫的間隔時間
[UIView setAnimationDuration:0.20];
//??使用當前正在運行的狀態開始下一段動畫
[UIView setAnimationBeginsFromCurrentState: YES];
//設置視圖移動的位移
self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y -100, self.view.frame.size.width, self.view.frame.size.height);
//設置動畫結束
[UIView commitAnimations];
}
//在UITextField 編輯完成調用方法
- (void)textFieldDidEndEditing:(UITextField *)textField
{
//設置動畫的名字
[UIView beginAnimations:@"Animation"context:nil];
//設置動畫的間隔時間
[UIView setAnimationDuration:0.20];
//??使用當前正在運行的狀態開始下一段動畫
[UIView setAnimationBeginsFromCurrentState: YES];
//設置視圖移動的位移
self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y +100, self.view.frame.size.width, self.view.frame.size.height);
//設置動畫結束
[UIView commitAnimations];
}
第二種方法:
//在UITextField 編輯之前調用方法
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self animateTextField: textField up: YES];
}
//在UITextField 編輯完成調用方法
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[self animateTextField: textField up: NO];
}
//視圖上移的方法
- (void) animateTextField: (UITextField *) textField up: (BOOL) up
{
//設置視圖上移的距離,單位像素
constintmovementDistance =100;// tweak as needed
//三目運算,判定是否需要上移視圖或者不變
intmovement = (up ? -movementDistance : movementDistance);
//設置動畫的名字
[UIView beginAnimations: @"Animation"context: nil];
//設置動畫的開始移動位置
[UIView setAnimationBeginsFromCurrentState: YES];
//設置動畫的間隔時間
[UIView setAnimationDuration:0.20];
//設置視圖移動的位移
self.view.frame = CGRectOffset(self.view.frame,0, movement);
//設置動畫結束
[UIView commitAnimations];
}
//點擊屏幕,讓鍵盤彈回
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}