【问题标题】:How to change the view's bounds within UIPresentationController?如何在 UIPresentationController 中更改视图的边界?
【发布时间】:2018-03-21 15:54:14
【问题描述】:

我使用UIPresentationController 的子类在屏幕上呈现一些控制器。我就是这样准备的:

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

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

看起来是这样的:

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

【问题讨论】:

  • 您是在问键盘何时响应您的视图应该缩小?
  • 我认为 preferredContentSize=CGRectMake(....) 会起作用。你试过吗?
  • 是的,我试过了,它没有改变任何东西:(
  • 使用 NSNotificationCenter ,在键盘启动时收到通知。然后试试上面的
  • 是的,我是这样做的,但那时没有调用frameOfPresentedViewInContainerView()

标签: ios swift


【解决方案1】:

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

【讨论】:

  • 是的,这个有效。更准确地说,从你做的部分视图控制器:presentationController?.containerView?.setNeedsLayout()。此外,如果您想要动画,请在键盘事件中调用layoutIfNeeded(),它会很好地动画。
【解决方案2】:

相对容易。

首先,您需要观察演示者的键盘变化

收听通知.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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    相关资源
    最近更新 更多