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

如何隐藏AVPictureInPictureController的默认关闭按钮?

问题描述

我使用AVPictureInPictureController实现了iOS画中画(PiP)功能,已经通过设置requiresLinearPlayback(iOS14+)隐藏了时间搜索栏,通过KVC设置controlsStyle隐藏了播放控件,但始终无法隐藏PiP窗口上的关闭按钮和返回按钮。开发时参考了UIPiPDemo项目,以下是我的核心实现代码:

// 初始化AVPictureInPictureController的核心代码
func start() {
    if AVPictureInPictureController.isPictureInPictureSupported() {
        _pipController = AVPictureInPictureController(
            contentSource: .init(
                sampleBufferDisplayLayer: pipUi.bufferDisplayLayer,
                playbackDelegate: self))
        _pipController?.delegate = self
        
        // 监听PiP可用性
        _pipPossibleObservation = _pipController?.observe(
            \AVPictureInPictureController.isPictureInPicturePossible,
             options: [.initial, .new],
             changeHandler: { [weak self] _, changed in
                 DispatchQueue.main.async {
                     if changed.newValue == true {
                         // 处理PiP可用逻辑
                     }
                 }
             })
    }
    
    if #available(iOS 14.0, *) {
        // 隐藏时间搜索栏
        _pipController?.requiresLinearPlayback = true
    }
    
    // 隐藏播放控件
    _pipController?.setValue(true, forKey: "controlsStyle")
}

我希望隐藏系统默认的关闭按钮,自行实现关闭PiP的自定义交互,恳请提供技术帮助。


解决方案

方法:通过KVC访问私有属性隐藏按钮

系统AVPictureInPictureController没有公开API直接控制关闭/返回按钮的显示,但可以通过KVC设置私有属性来隐藏它们。在你的start()方法中添加以下代码:

func start() {
    // ... 现有代码 ...
    
    // 隐藏关闭按钮
    _pipController?.setValue(false, forKey: "showsCloseButton")
    // 隐藏返回按钮(如果不需要的话)
    _pipController?.setValue(false, forKey: "showsReturnButton")
}

重要注意事项

  1. 审核风险:showsCloseButton和showsReturnButton是私有API,使用这些属性可能导致App Store审核被拒绝。如果你的应用需要上架,建议谨慎使用,或仅用于内部测试场景。
  2. 合规要求:根据苹果人机交互指南(HIG),画中画窗口必须提供清晰的关闭途径。隐藏系统关闭按钮后,你必须自行实现关闭逻辑,例如:
    • 添加自定义手势(如双击PiP窗口触发关闭)
    • 通过通知中心触发toggle()方法
    • 在应用主界面提供关闭按钮

替代方案(无审核风险)

如果担心私有API的审核问题,你可以考虑:

  • 保留系统关闭按钮,在pictureInPictureControllerDidStopPictureInPicture代理方法中拦截关闭事件,执行自定义逻辑后再完成关闭流程。
  • 实现自定义画中画容器(非系统级PiP),但这种方式无法享受系统级的多任务切换支持,仅适用于特定场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:36:19