当键盘到位时移动UIScrollView

当键盘到位时移动UIScrollView

问题描述:

[编辑:]问题已解决。我没有在UIBuilder中正确链接我的代表。代码很好!当键盘到位时移动UIScrollView

我想在键盘出现时调整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 .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]; 
    } 
} 
+0

非常感谢,的代码段包含的一切,我需要:) – matehat 2013-06-28 18:39:54

+2

你可以使用[KBKeyboardObserver(https://github.com/kam800/KBKeyboardObserver)库来观察键盘事件。 – kam800 2013-11-06 20:37:24

您是否曾经为该特定通知添加了观察者?请确保您的loadView方法你这样做:

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

不要忘记注销上述观察员viewDidUnload方法是这样的:

[[NSNotificationCenter defaultCenter] removeObserver:self]; 

让我知道你的作品了!

+0

我确实添加了观察者,正如我所提到的,我可以看到键盘显示时调用的函数,所以我确实知道观察者正在工作。谢谢虽然总是很好地复查事情, – thenetimp 2011-12-21 19:30:47

+2

您需要更新此信息。 viewDidUnload不再被调用。 – 2013-10-20 12:57:42

您可能希望尝试强烈推荐“TPKeyboardAvoidingScrollView”,可从以下https://github.com/michaeltyson/TPKeyboardAvoiding

就像一个魅力...

+1

+1易于实施,真的很好。我建议将它与BSKeyboardControl结合在文本字段中添加导航控件:http://www.cocoacontrols.com/controls/bskeyboardcontrols – Groot 2013-03-20 11:13:07

+0

@Reuven当使用TPKeyboardAvoidingScrollview时,有时如果我们在textview中复制并粘贴,视图完全上升。 。有没有解决方案? – 2014-02-21 14:03:48

+1

它是否与'UIPresentationModeFormSheet'协同工作? – fatuhoku 2014-05-08 14:24:08

我已经与UITableView做过几次(这只是一个扩展UIScrollView)。你可以找到code in this answer

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

setupKeyboardNotifcationListenerForScrollView(scrollView) 

它会自动自动调整键盘出现时。无需任何子类,只是一个扩展!它availble的由GitHub SingleLineKeyboardResize