blog.csdn.net/iorchid/article/details/6561862
键盘弹出时textfield也随着上移,键盘隐藏时,textfield回到原来的位置
_tspasswordTF = [[UITextField alloc] initWithFrame: CGRectMake(100, 150, 60, 30)];
_tspasswordTF.backgroundColor = [UIColor redColor];
_tspasswordTF.tag = 2;
_tspasswordTF.delegate = self;
[self.view addSubview: _tspasswordTF];
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self animateTextField: textField up: YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[self animateTextField: textField up: NO];
[textField resignFirstResponder];
return YES;
}
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
const int movementDistance = 80; // tweak as needed
const float movementDuration = 0.3f; // tweak as needed
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: nil context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}
_tspasswordTF = [[UITextField alloc] initWithFrame: CGRectMake(100, 150, 60, 30)];
_tspasswordTF.backgroundColor = [UIColor redColor];
_tspasswordTF.tag = 2;
_tspasswordTF.delegate = self;
[self.view addSubview: _tspasswordTF];
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self animateTextField: textField up: YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[self animateTextField: textField up: NO];
[textField resignFirstResponder];
return YES;
}
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
const int movementDistance = 80; // tweak as needed
const float movementDuration = 0.3f; // tweak as needed
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: nil context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}