键盘到位后移动UIScrollView

the*_*imp 15 iphone keyboard objective-c ipad ios

[编辑:]问题已经解决.我没有正确链接我的代表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所以我看到函数实际上被调用了,但是当我尝试NSLog使用kbSize.height时,它的值总是为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];
    }
}
Run Code Online (Sandbox Code Playgroud)

Reu*_*ven 33

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

奇迹般有效...


Mih*_*atu 3

您是否曾为该特定通知添加过观察者?确保在您的loadView方法中执行以下操作:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
Run Code Online (Sandbox Code Playgroud)

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

[[NSNotificationCenter defaultCenter] removeObserver:self];
Run Code Online (Sandbox Code Playgroud)

让我知道是否有效!

  • 您需要更新这篇文章。viewDidUnload 不再被调用。 (2认同)