繁体   English   中英

UIView动画设置框架在iOS 8中不起作用

[英]UIView animation set frame not working in iOS 8

当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

怎么了?

这不是管理键盘的方式。 您不应该更改viewcontroller视图的框架。 您应该在视图中添加滚动视图,并在显示或隐藏键盘时调整内容插入。

当要求显示键盘时,系统从屏幕底部将其滑入并放置在应用程序的内容上。 由于它位于内容的顶部,因此可以将键盘置于用户想要编辑的文本对象的顶部。 发生这种情况时,您必须调整内容,以使目标对象保持可见。

调整内容通常涉及临时调整一个或多个视图的大小并对其进行定位,以使文本对象保持可见。 用键盘管理文本对象的最简单方法是将它们嵌入UIScrollView对象(或其子类之一,如UITableView)中。 显示键盘时,您要做的就是重置滚动视图的内容区域并将所需的文本对象滚动到适当的位置。 因此,响应UIKeyboardDidShowNotification,您的处理程序方法将执行以下操作:

  1. 获取键盘的大小。
  2. 通过键盘高度调整滚动视图的底部内容插图。
  3. 将目标文本字段滚动到视图中。
 // 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;
}

您可以在官方文档中找到更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM