3

当键盘变得可见时,我需要UIPresentationController使用动画调整呈现的自定义视图的框架。

由于自动添加的约束,动画似乎不起作用。我试图通过修改这些约束来创建动画,但失败了。

在过去的 8 个小时里,我一直在尝试解决这个问题,但失败了。在文档中也找不到任何有用的信息UIPresentationController。谁能给我一些建议如何解决这个问题?

我试图重现类似于 modalPresentationStyle .Popover 的效果。只需减少框架高度和原点,这样键盘就不会覆盖任何内容。

我希望框架在键盘出现时适应。

PresentedVC示例:

import UIKit
class CustomSaleViewController: UIViewController {

private let animationDuration: Double = 0.5

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    modalPresentationStyle = UIModalPresentationStyle.Custom
}


private var originalFrameBeforeKeyboardAppread: CGRect?
func keyboardWillShow(notification: NSNotification) {

    if originalFrameBeforeKeyboardAppread == nil { originalFrameBeforeKeyboardAppread = view.frame }

    let keyboardHeight = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue.height
    let remainingVisibleHeight = Utils.window()!.frame.height - keyboardHeight
    let preferedSpacing: CGFloat = 20
    let maxHeight = remainingVisibleHeight - preferedSpacing * 2

    if remainingVisibleHeight > view.frame.height - preferedSpacing {
        UIView.animateWithDuration(animationDuration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut , animations: {
            self.view.frame.origin.y = preferedSpacing
            self.view.frame.size.height = maxHeight
            }, completion: nil)
    }
}

func keyboardWillHide(notification: NSNotification) {
    if originalFrameBeforeKeyboardAppread != nil {
        UIView.animateWithDuration(animationDuration, animations: {
            self.view.frame = self.originalFrameBeforeKeyboardAppread!
            }, completion: nil)
    }
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

}
4

0 回答 0