在學習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{ //設定視圖上移的距離,單位像素 const int movementDistance = 100; // tweak as needed //三目運算,判定是否需要上移視圖或者不變 int movement = (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];}