键盘关闭时滚动视图不向下滚动

时间:2014-07-10 01:39:25

标签: ios keyboard

我在移动键盘下的内容上使用了苹果指南

Guide here

当键盘打开时向上滚动效果非常好但键盘关闭时它不会向下滚动,而是滚动视图的顶部被切断。

我的代码

// 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);
    _myScrollView.contentInset = contentInsets;
    _myScrollView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
        [self.myScrollView scrollRectToVisible:activeField.frame animated:YES];
    } 
}

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

2 个答案:

答案 0 :(得分:2)

这是我在键盘辞职时使用的代码。我的原始代码有问题,因为它似乎不想在iOS 7中工作。

-(void) keyboardWillHide:(NSNotification *)note
{
    // Get the keyboard size
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];

    CGRect frame = self.scrollView.frame;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];

    //add keyboard size to current scrollview frame
    frame.size.height += keyboardBounds.size.height;

    //apply frame to scrollview
    self.scrollView.frame = frame;

    [UIView commitAnimations];
}

答案 1 :(得分:0)

urnotsam 提供的Swift 2.0代码转换目标C代码:

func keyboardWillBeHidden(notification: NSNotification) {
    // Once keyboard disappears, restore original positions
    let info: NSDictionary = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var scrollViewFrame: CGRect = self.scrollView.frame

    // Begin animation
    UIView.beginAnimations(nil, context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(0.3)

    scrollViewFrame.size.height += (keyboardSize?.height)!
    // Apply it
    self.scrollView.frame = scrollViewFrame
    // Now animate
    UIView.commitAnimations()
}