如何让SwiftUI中的PDFView适配深色模式实现颜色反转?
在SwiftUI中实现PDFView深色模式颜色反转(白字黑底)
针对你的需求,这里提供两种可靠的实现方案:
方法一:SwiftUI修饰符实现条件颜色反转
利用SwiftUI的colorInvert()修饰符,结合环境变量判断当前颜色模式,仅在深色模式下反转视图颜色:
struct ContentView: View { @Environment(\.colorScheme) var colorScheme var body: some View { guard let url = Bundle.main.url(forResource: "example", withExtension: "pdf") else { return Text("PDF文件不存在") } PDFKitView(url) .modifier(DarkModeInvertModifier()) } } // 自定义修饰符:仅在深色模式下应用颜色反转 struct DarkModeInvertModifier: ViewModifier { @Environment(\.colorScheme) var colorScheme func body(content: Content) -> some View { content .colorInvert() .opacity(colorScheme == .dark ? 1 : 0) .overlay( content .opacity(colorScheme == .light ? 1 : 0) ) } }
方法二:UIKit子类化PDFView实现滤镜反转
在UIKit层面处理,通过给PDFView图层添加颜色反转滤镜,根据系统颜色模式动态切换,可避免反转PDFView控件(如滚动条)的颜色:
- 创建自定义PDFView子类,处理 trait 变化:
class InvertiblePDFView: PDFView { override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) // 根据当前颜色模式切换滤镜 if traitCollection.userInterfaceStyle == .dark { let invertFilter = CIFilter(name: "CIColorInvert") self.layer.filters = [invertFilter] } else { self.layer.filters = nil } } }
- 修改UIViewRepresentable使用自定义子类:
struct PDFKitView: UIViewRepresentable { let url: URL init(_ url: URL) { self.url = url } func makeUIView(context: Context) -> InvertiblePDFView { let pdfView = InvertiblePDFView() pdfView.document = PDFDocument(url: self.url) pdfView.autoScales = true pdfView.displayMode = .singlePage pdfView.displayDirection = .horizontal pdfView.usePageViewController(true) pdfView.tintColor = .red return pdfView } func updateUIView(_ uiView: InvertiblePDFView, context: Context) { // 系统切换模式时会自动触发traitCollectionDidChange,无需额外处理 } }
注意事项
- 方法一的
colorInvert()会反转整个视图的所有颜色,包括PDF内容和控件;方法二仅反转PDF页面内容,控件颜色保持原样。 - 包含彩色图片的PDF反转后可能显示异常,可根据实际需求选择方案。
内容的提问来源于stack exchange,提问作者alionthego
相关产品推荐
相关产品推荐

