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

iOS13升级后UIPopover内嵌UIActionSheet样式AlertController尺寸异常问题

解决方案:iOS13后UIPopover中UIActionSheet样式UIAlertController的尺寸异常问题

我之前也碰到过这个iOS13升级后的坑,折腾了好一会儿才找到靠谱的解决办法,分享给你:

问题根源

iOS13对UIAlertController的自适应布局逻辑做了调整,当在UIPopover环境下使用.actionSheet样式的弹窗时,系统会自动计算内容尺寸,但这个计算逻辑有时候会出现偏差,导致popover的大小变得不符合预期。

两种有效解决方法

方法一:设置固定的preferredContentSize

直接给UIAlertController指定固定的宽高,强制约束popover的尺寸:

// 创建ActionSheet样式的AlertController
let actionSheetAlert = UIAlertController(title: "操作选项", message: nil, preferredStyle: .actionSheet)

// 添加你的操作按钮
actionSheetAlert.addAction(UIAlertAction(title: "取消", style: .cancel))
actionSheetAlert.addAction(UIAlertAction(title: "删除", style: .destructive))
actionSheetAlert.addAction(UIAlertAction(title: "编辑", style: .default))

// 关键:设置固定的内容尺寸,根据你的需求调整数值
actionSheetAlert.preferredContentSize = CGSize(width: 320, height: 220)

// 配置并呈现Popover
if let popoverPresenter = actionSheetAlert.popoverPresentationController {
    popoverPresenter.sourceView = yourTriggerButton // 替换成你的触发视图
    popoverPresenter.sourceRect = yourTriggerButton.bounds
    popoverPresenter.permittedArrowDirections = .up // 按需设置箭头方向
}

present(actionSheetAlert, animated: true)

方法二:通过代理强制保持Popover样式

利用UIPopoverPresentationControllerDelegate的方法,阻止系统将ActionSheet自动转为全屏布局,保持popover的原有样式:

// 让你的ViewController遵循代理协议
class YourViewController: UIViewController, UIPopoverPresentationControllerDelegate {

    func showActionSheet() {
        let actionSheetAlert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        // 添加操作按钮...
        actionSheetAlert.addAction(UIAlertAction(title: "取消", style: .cancel))
        actionSheetAlert.addAction(UIAlertAction(title: "分享", style: .default))

        if let popoverPresenter = actionSheetAlert.popoverPresentationController {
            popoverPresenter.sourceView = self.view
            popoverPresenter.sourceRect = CGRect(x: self.view.frame.midX, y: self.view.frame.midY, width: 0, height: 0)
            popoverPresenter.delegate = self // 设置代理
        }

        present(actionSheetAlert, animated: true)
    }

    // 强制保持Popover样式,不自动适配为全屏
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
    }
}

额外提示

如果你的ActionSheet内容动态变化,可以根据实际内容计算合适的preferredContentSize,比如通过遍历action的高度来累加计算总高度,这样既固定了尺寸又能适配内容变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:00:37