如何在UIPresentationController中更改视图的界限?

时间:2016-07-13 08:51:03

标签: ios swift

我使用UIPresentationController的子类在屏幕上显示一些控制器。这就是我准备它的方式:

controller.transitioningDelegate = self
controller.modalPresentationStyle = .Custom
presentViewController(controller, animated: true, completion: nil)

但是在控制器中有一个textField,我在那里添加了UIKeyboardDidShowNotification的观察者。键盘出现时是否可以更新视图的框架?

这就是它的样子:

enter image description here

由于键盘,我需要更改该视图的界限。

2 个答案:

答案 0 :(得分:1)

相对容易。

首先,您需要观察演示者中的键盘更改

收听通知.UIKeyboardWillShow, .UIKeyboardDidShow, .UIKeyboardWillHide, .UIKeyboardDidHide

我建议为此创建一个KeyboardObserver类,例如静态实例,并将键盘变量(帧,动画速度等)存储在那里,并在该类上添加一个委托以通知您键盘更改。

然后你最终得到类似的东西

extension PresentationController: KeyboardManagerDelegate {
    internal func keyboardManager(_ manager: KeyboardManager, action: KeyboardManager.KeyBoardDisplayAction, info: KeyboardManager.Info) {
        guard let containerView = containerView else { return }

        UIView.animate(withDuration: info.animationDuration, delay: 0, options: info.animationOptions, animations: {
            containerView.setNeedsLayout()
            containerView.layoutIfNeeded()
        }, completion: nil)
    }
}

接下来,您需要覆盖frameOfPresentedViewInContainerView

示例:

override var frameOfPresentedViewInContainerView: CGRect {
    guard let containerView = containerView else {
        return .zero
    }

    let desiredSize = CGSize(width: 540, height: 620)

    let width = min(desiredSize.width, containerView.width)
    let x = round((containerView.width - width) / 2)

    if KeyboardManager.shared.isKeyboardVisible {
        let availableHeight = containerView.height - KeyboardManager.shared.keyboardFrame.height
        let height = availableHeight - 40

        return CGRect(x: x, y: 25, width: width, height: height)
    } else {
        let height = min(desiredSize.height, containerView.height)

        let y = round((containerView.height - height) / 2)

        return CGRect(x: x, y: y, width: width, height: height)
    }
}

最后还实现了一种布局方法来更新视图

override func containerViewWillLayoutSubviews() {
    super.containerViewWillLayoutSubviews()

    presentedView?.frame = frameOfPresentedViewInContainerView
}

答案 1 :(得分:0)

containerView?.setNeedsLayout()需要在我改变后调用。