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

模态呈现Loader视图控制器时出现黑色背景问题求助

解决模态Loader背景变黑的问题

嘿,我帮你排查了这个背景变黑的问题,主要是模态展示的样式配置没到位,咱们来一步步修正:

问题根源

你之前的代码里有两个关键问题:

  1. 使用了.currentContext作为模态样式,这个样式依赖当前ViewController的上下文,很容易导致背景出现黑色;
  2. 错误地给调用present的ViewController设置了modalPresentationStyle,而不是给Loader本身设置。

修正后的代码

第一步:修改Loader类

把模态样式换成.overFullScreen(这个样式允许Loader覆盖全屏同时保持背景透明),同时优化指示器的约束写法:

class Loader: UIViewController, NVActivityIndicatorViewable { 
    override func viewDidLoad() { 
        super.viewDidLoad() 
        // 关键:使用overFullScreen确保背景透明生效
        self.modalPresentationStyle = .overFullScreen 
        self.view.backgroundColor = .clear 

        // 初始化指示器时不用手动算frame,用约束更可靠
        let activityIndicatorView = NVActivityIndicatorView(
            frame: .zero, 
            type: .lineScale, 
            color: GlobalVariables.stacksBlue, 
            padding: 20
        )
        self.view.addSubview(activityIndicatorView)
        activityIndicatorView.startAnimating()
        activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
        
        // 激活约束,包括宽高和居中
        NSLayoutConstraint.activate([
            activityIndicatorView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            activityIndicatorView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            activityIndicatorView.widthAnchor.constraint(equalToConstant: 100),
            activityIndicatorView.heightAnchor.constraint(equalToConstant: 100)
        ])
    } 
}

第二步:修正UIViewController扩展

不需要给当前VC设置模态样式,只需要确保Loader实例的样式正确(这里可以再重复设置一次,避免意外):

extension UIViewController { 
    func showLoader() { 
        let loader = Loader()
        // 再次确认Loader的模态样式,确保透明生效
        loader.modalPresentationStyle = .overFullScreen
        self.present(loader, animated: false, completion: nil) 
    } 

    func hideLoader() { 
        self.dismiss(animated: false, completion: nil) 
    } 
}

为什么这样能解决问题?

  • .overFullScreen是专门用于在全屏上方叠加透明视图的模态样式,它会忽略底层VC的背景设置,直接让你的Loader背景透明生效;
  • 把模态样式设置在Loader实例上,不会影响当前VC后续的其他模态展示操作,避免引入新的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:39:17