当iOS中的键盘弹出时,我会在当前UIViewController
中向上移动视图,我已经实现了它,但是有一些错误。
我接收了名为UIKeyboardWillShowNotification
的通知:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "showKeyBoard:", name: UIKeyboardWillShowNotification, object: nil)
在showKeyBoard
中运行提升功能:
func showKeyBoard(notify:NSNotification){
if let userInfo = notify.userInfo{
let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
var keyboardFrameEnd = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()
keyboardFrameEnd = self.view.convertRect(keyboardFrameEnd!, fromView: nil)
UIView.animateWithDuration(duration! , animations: { () -> Void in
self.view.frame = CGRectMake(0, -keyboardFrameEnd!.size.height, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))
})
}
}
现在我发现它可以在iOS7中运行,但在iOS8中它无效。
我尝试添加
self.view.setTranslatesAutoresizingMaskIntoConstraints(true)
viewDidLoad
中的。
会发生什么?
答案 0 :(得分:3)
这不是你应该如何管理键盘。你不应该改变viewcontroller视图的框架。您应该向视图添加滚动视图,并在显示或隐藏键盘时调整内容插入。
当系统要求您显示键盘时,系统会将其从屏幕底部滑入,并将其放在应用内容上。因为它位于您的内容之上,所以键盘可以放在用户想要编辑的文本对象的顶部。发生这种情况时,您必须调整内容,以使目标对象保持可见。
调整内容通常涉及暂时调整一个或多个视图的大小并对其进行定位,以使文本对象保持可见。使用键盘管理文本对象的最简单方法是将它们嵌入到UIScrollView对象(或其子类之一,如UITableView)中。显示键盘时,您所要做的就是重置滚动视图的内容区域并将所需的文本对象滚动到位。因此,为了响应UIKeyboardDidShowNotification,您的处理程序方法将执行以下操作:
- 获取键盘的大小。
- 按键盘高度调整滚动视图的底部内容插入。
- 将目标文本字段滚动到视图中。
醇>
// 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);
scrollView.contentInset = contentInsets;
scrollView.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.scrollView scrollRectToVisible:activeField.frame animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
您可以在官方documentation
中找到更多信息