Move specific UITextField when the Keyboard show

2019-09-06 01:09发布

问题:

I followed the Apple documentation to move a textfield upwards when the keypad appears. The code works fine my problem is that I need that one specific textfield is moved towards the other, instead of implementing the code Apple every textfield I select is moved upwards ... How can I do to move a specific textField and not all?

Thank you very much, I insert the following code used

-(void)viewWillAppear:(BOOL)animated 
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];

}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification {
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect bkgndRect = changePasswordTextField.superview.frame;
    bkgndRect.size.height -= kbSize.height;
    [scrollView setContentOffset:CGPointMake(0.0, changePasswordTextField.frame.origin.y+kbSize.height) animated:YES];
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification {


    [scrollView setContentOffset:CGPointZero animated:YES];
}

回答1:

You can achieve your functionality by following steps.

  1. Set delegate of your UITextField.
  2. Implement textFieldDidBeginEditing method which will be called when keyboard open for textfield. So you may change frame of textfield in this method as below.

    -(void)textFieldDidBeginEditing:(UITextField *)textField{
         [textField setFrame:CGRectMake(0.0, textField.frame.origin.y-VALUE,textField.frame.size.width,textField.frame.size.height) animated:YES];
         // VALUE = textfield you want to move upward vertically
    }
    
  3. Now, to handle keyboard hiding event, you can set frame of your textfield to its origin in textFieldDidEndEditing method as below.

    - (void)textFieldDidEndEditing:(UITextField *)textField{
          [textField setFrame:CGRectMake(0.0, textField.frame.origin.y+VALUE,textField.frame.size.width,textField.frame.size.height) animated:YES];
          // VALUE = textfield you want to move downward vertically
    }
    

I hope it may help you.