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

PDFKit适配PDF文档深色模式:设置overrideUserInterfaceStyle为.dark无效果怎么办

问题根因

你设置的overrideUserInterfaceStyle仅会修改PDFView本身的UI元素(比如滚动条、空白占位背景)的外观,不会影响PDF文档内部的内容渲染逻辑,PDF内容默认会保留原始文件的配色(通常是白底黑字),所以单独设置这个属性看不到效果。

解决方案

方案1:兼容所有iOS版本的通用实现

通过图层混合滤镜实现PDF内容的颜色反转,不需要依赖私有API,iOS 12及以上版本都可以使用:

let pdfView = PDFView()        
pdfView.overrideUserInterfaceStyle = .dark
// 关闭默认页阴影,避免深色模式下出现白色边框
pdfView.pageShadowsEnabled = false
pdfView.backgroundColor = .black

guard let documentUrl = Bundle.main.url(forResource: "mPilot", withExtension: "pdf") else { return }         
guard let document = PDFDocument(url: documentUrl) else { return }
            
pdfView.document = document

// 深色模式下开启内容反转
if traitCollection.userInterfaceStyle == .dark {
    pdfView.layer.compositingFilter = "differenceBlendMode"
} else {
    pdfView.layer.compositingFilter = nil
}

如果需要跟随系统深色模式切换自动更新,追加以下方法:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
    guard traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) else { return }
    pdfView.layer.compositingFilter = traitCollection.userInterfaceStyle == .dark ? "differenceBlendMode" : nil
}

方案2:iOS 15+ 私有API方案(不推荐上架使用)

如果是内部工具类应用,可以用私有API实现反转,效果和系统一致:

if #available(iOS 15.0, *) {
    pdfView.documentView?.setValue(true, forKey: "invertColors")
}

注意事项

  • 图层混合方案会反转所有颜色,如果你需要保留PDF原有的彩色内容,可以在渲染PDF时手动遍历每页调整上下文填充色,实现仅反转背景和文字颜色的效果。
  • 部分加密、带自定义矢量层的PDF可能会出现渲染异常,可以通过调整pdfView.interpolationQuality属性优化渲染效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:15:03