1

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

代码:

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

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

看法

4

2 回答 2

3

为此,您可以忽略键盘显示/隐藏通知,只使用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;
}
于 2013-05-17T14:28:12.060 回答
0
– (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.
  }
于 2013-05-18T05:29:39.910 回答