繁体   English   中英

UITextField在键盘阻止时移动

[英]UITextField moving when keyboard will block it

我试图这样做,以便当您单击电子邮件字段并弹出键盘时,它将向上移动视图。 但是现在使用此代码,无论我点击什么文本字段,它都会移动视图。 我也不能让键盘解雇。 不确定如何将此代码设置为仅滚动到活动字段?

码:

- (void)registerForKeyboardNotifications
{
    [[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;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, self.emailField.frame.origin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, self.emailField.frame.origin.y-kbSize.height);
        [scrollView setContentOffset:scrollPoint animated:YES];
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
}

我有一个看起来像这样的视图(它在滚动视图上)

视图

为此,您可以忽略键盘显示/隐藏通知,只需使用UITextFieldDelegate协议:

– (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if([textField isEqual:self.emailTextField]){
        // scroll up
    }
    return true;
}

– (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if([textField isEqual:self.emailTextField]){
        // scroll back to start
    }
    return true;
}
– (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if([textField isEqual:YourTextfieldName])
{

}
return true;      // return true is needed.
}

 – (BOOL)textFieldShouldEndEditing:(UITextField *)textField 
  {
   if([textField isEqual:YourTextfieldName])
      {

      }
   return true;    //return true is needed.
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM