键盘到位后移动UIScrollView

时间:2011-12-21 13:34:58

标签: iphone objective-c ios ipad keyboard

[编辑:]问题已经解决了。我没有在UIBuilder中正确链接我的代理人。代码很好!

我正在尝试在键盘出现时调整scrollview的大小。我去了开发人员文档并找到了这些信息。

http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html#//apple_ref/doc/uid/TP40009542-CH5-SW1

在左侧“管理键盘”。

在文档中,它显示了一些代码来检测键盘的大小,然后调整UIScrollView的大小。我在函数NSLog的代码中放了一条- (void)keyboardWasShown:(NSNotification*)aNotification消息,所以我看到该函数实际上已被调用,但当我尝试NSLogkbSize。它的值总是为0。

为什么苹果为此目的提供的代码不起作用?

- (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, activeField.frame.origin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height);
        [scrollView setContentOffset:scrollPoint animated:YES];
    }
}

4 个答案:

答案 0 :(得分:33)

您可能需要尝试强烈推荐的“TPKeyboardAvoidingScrollView”,可从以下网址获取:https://github.com/michaeltyson/TPKeyboardAvoiding

像魅力一样......

答案 1 :(得分:3)

您是否曾为该特定通知添加了观察者?请确保使用loadView方法执行此操作:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];

不要忘记在viewDidUnload方法取消注册观察者,如下所示:

[[NSNotificationCenter defaultCenter] removeObserver:self];

让我知道这是否成功!

答案 2 :(得分:0)

我已经使用UITableView(这只是一个扩展的UIScrollView)多次完成此操作。你可以找到code in this answer

答案 3 :(得分:0)

一个简单的解决方案是将扩展UIViewController + Keyboard.swift添加到项目中,只需一行

setupKeyboardNotifcationListenerForScrollView(scrollView)

键盘出现时会自动自动调整大小。不需要任何子类,只是一个扩展!它可以在GitHub上使用SingleLineKeyboardResize

相关问题