相对容易。
首先,您需要观察演示者的键盘变化
收听通知.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
}