You need to enable JavaScript to run this app. Swift 5 实现Flutter项目在applicationWillResignActive中展示自定义白底遮挡图片
优惠活动
大模型
产品
解决方案
定价
更多

Swift 5 实现Flutter项目在applicationWillResignActive中展示自定义白底遮挡图片

自定义图片资源存放位置
  • 用Xcode打开项目ios目录下的.xcworkspace文件,在左侧导航栏找到Runner分组下的Assets.xcassets
  • 右键点击Assets.xcassets的空白区域,选择新建Image Set,将其重命名为便于识别的名称,比如app_mask
  • 将准备好的白底蒙版图片(建议同步提供2x、3x分辨率版本,适配不同尺寸的iOS设备)拖入Image Set对应的分辨率占位框中即可
    注意:不要将图片放到Flutter的assets目录下,原生Swift代码直接读取iOS原生Asset目录的资源无需额外配置跨端映射逻辑,开发成本更低。
代码修改方案
  • 替换原有的模糊视图属性为图片视图属性
  • 调整进入后台时的视图创建逻辑,直接读取Asset中的图片生成全屏蒙版
  • 恢复前台时的移除逻辑无需大幅调整,沿用原tag查找的逻辑即可

修改后的完整AppDelegate代码:

import UIKit
import Flutter
import Firebase

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  // 可保留原tag值,也可修改为更语义化的命名
  let TAG_MASK_VIEW = 12345
  // 替换原模糊视图为图片视图
  var maskImageView: UIImageView?

  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    FirebaseApp.configure()
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  override func applicationWillResignActive(_ application: UIApplication) {
    // 先移除已存在的旧蒙版
    if let view = self.window.rootViewController?.view.subviews.first(where: {$0.tag == TAG_MASK_VIEW}){
        view.removeFromSuperview()
        maskImageView = nil
    }
    if maskImageView == nil {
        // 初始化全屏图片蒙版
        maskImageView = UIImageView(frame: UIScreen.main.bounds)
        // 读取Asset中的图片,将后面的"app_mask"替换为你自己的Image Set名称
        maskImageView?.image = UIImage(named: "app_mask")
        // 图片填充模式可按需调整
        maskImageView?.contentMode = .scaleToFill
        maskImageView?.tag = TAG_MASK_VIEW
        // 兜底白底,避免图片透明区域露出App内容
        maskImageView?.backgroundColor = .white
    }
    self.window.rootViewController?.view.insertSubview(maskImageView!, at: 0)
  }

  override func applicationDidBecomeActive(_ application: UIApplication) {
    // 恢复前台时移除蒙版
    if let view = self.window.rootViewController?.view.subviews.first(where: {$0.tag == TAG_MASK_VIEW}){
        view.removeFromSuperview()
        maskImageView = nil
    }
  }
}
注意事项
  • 若蒙版图片本身为完整白底,可省略backgroundColor = .white的兜底配置
  • 图片填充模式可根据实际需求替换:
    • .aspectFit:按比例完整显示图片,不会裁切也不会变形
    • .aspectFill:按比例铺满全屏,多余部分自动裁切
    • .scaleToFill:强制拉伸铺满全屏,可能导致图片变形
  • 无需配置Flutter资源通道,原生代码直接调用iOS Asset资源即可,无需处理跨端资源交互

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.05 14:54:03