键盘到位时移动UIScrollView
[编辑]问题已解决。 我没有在UIBuilder
正确链接我的代表。 代码是好的!
我正在尝试调整键盘出现时滚动视图。 我去了开发人员的文档,并find这个信息。
http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html#//apple_ref/doc/uid/TP40009542-CH5-SW1
在左边的“pipe理键盘”。
在文档中,它显示了一些代码来检测键盘的大小,然后调整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]; } }
你可能想尝试强烈推荐的“TPKeyboardAvoidingScrollView”,可以从: https : //github.com/michaeltyson/TPKeyboardAvoiding
奇迹般有效…
你有没有添加一个观察员的具体通知? 确保你的loadView
方法是这样的:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
不要忘记在viewDidUnload
方法上取消注册观察者,如下所示:
[[NSNotificationCenter defaultCenter] removeObserver:self];
让我知道如果这个工程出来!
我用UITableView
(这只是一个扩展的UIScrollView
)做了几次。 你可以在这个答案中find代码 。
一个简单的解决scheme是用一行代码将扩展UIViewController + Keyboard.swift添加到您的项目中
setupKeyboardNotifcationListenerForScrollView(scrollView)
出现键盘时会自动resize。 不需要任何子类,只是一个扩展! 它可用于GitHub SingleLineKeyboardResize