键盘显示时移动特定的 UITextField

Move specific UITextField when the Keyboard show

我按照 Apple 文档在键盘出现时向上移动了一个文本字段。 代码工作正常我的问题是我需要将一个特定的文本字段移向另一个文本字段,而不是实现代码 Apple 每个文本字段我 select 向上移动......我该怎么做才能移动特定的文本字段和不是全部?

非常感谢,我插入下面的代码用到了

-(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. 设置 UITextField 的委托。
  2. 实现 textFieldDidBeginEditing 方法,该方法将在为文本字段打开键盘时调用。所以你可以在这个方法中改变文本框的框架,如下所示。

    -(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. 现在,要处理键盘隐藏事件,您可以在 textFieldDidEndEditing 方法中将文本字段的框架设置为其原点,如下所示。

    - (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
    }
    

希望对您有所帮助