You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整模态弹出的ViewController,使其呈现效果如示例图所示?

解决模态ViewController自定义呈现位置的问题

你之前在viewDidLoad里修改frame无效的原因是:模态ViewController的view在viewDidLoad阶段还未被添加到系统的呈现容器中,后续系统会在布局流程(比如viewWillLayoutSubviews、viewDidLayoutSubviews)里根据默认的模态样式重置frame,所以你的设置会被覆盖。

下面是两种可行的解决方案:

方案一:自定义UIPresentationController(推荐,更稳定)

这种方法通过自定义呈现控制器,直接控制模态视图的最终frame,不受系统布局干扰。

  1. 创建自定义的PresentationController子类
class CustomPresentationController: UIPresentationController {
    // 重写此方法定义模态视图的位置和大小
    override var frameOfPresentedViewInContainerView: CGRect {
        guard let container = containerView else { return super.frameOfPresentedViewInContainerView }
        let topOffset: CGFloat = 100 // 顶部留空100pt
        return CGRect(
            x: 0,
            y: topOffset,
            width: container.bounds.width,
            height: container.bounds.height - topOffset
        )
    }
}
  1. 在你的模态ViewController中关联这个自定义控制器
class YourModalVC: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white // 设置背景色方便区分
    }

    // 返回自定义的呈现控制器
    override func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return CustomPresentationController(presentedViewController: presented, presenting: presenting)
    }
}
  1. 弹出模态VC时设置正确的呈现样式
let modalVC = YourModalVC()
modalVC.modalPresentationStyle = .custom // 必须设置为.custom才能使用自定义控制器
present(modalVC, animated: true)

方案二:在布局阶段调整frame(快速临时方案)

如果不想自定义PresentationController,可以在视图即将布局的阶段修改frame,这个阶段系统已经完成了初始布局,你的设置不会被轻易覆盖:

class YourModalVC: UIViewController {
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        guard let superView = view.superview else { return }
        let topOffset: CGFloat = 100
        view.frame = CGRect(
            x: 0,
            y: topOffset,
            width: superView.bounds.width,
            height: superView.bounds.height - topOffset
        )
    }
}

弹出时同样需要注意:如果你的项目是iOS 13+,默认的pageSheet样式可能会有自带的圆角和缩起效果,如果你需要完全自定义,建议设置modalPresentationStyle = .fullScreen或者.custom。

内容的提问来源于stack exchange,提问作者Alexander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 16:22:38