Move specific UITextField when the Keyboard show

牧云@^-^@ 提交于 2020-01-17 08:56:20

问题


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.



来源:https://stackoverflow.com/questions/29141340/move-specific-uitextfield-when-the-keyboard-show

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!