Files
Cable/Cable/Loads/QuickLookPreview.swift
Stefan Lange-Hegermann 695d2ccd75 Show action buttons in export previews
QLPreviewController only renders its share, print and open-in actions
when it is inside a navigation controller, so diagram and report
previews were dead ends. Wrap it in one, add an explicit Done button
and assert both in a UI test.
2026-08-12 11:48:39 +02:00

68 lines
2.2 KiB
Swift

//
// QuickLookPreview.swift
// Cable
//
import QuickLook
import SwiftUI
import UIKit
/// Presents a single exported file (PDF or PNG) in Quick Look so the user can
/// inspect it before sharing.
///
/// SwiftUI's `quickLookPreview(_:)` modifier is macOS-only, so iOS wraps
/// `QLPreviewController` directly. The controller only shows its action
/// buttons — share, print, open in another app — when it sits inside a
/// navigation controller, so it is wrapped in one and gets an explicit Done
/// button to close the sheet.
struct QuickLookPreview: UIViewControllerRepresentable {
let url: URL
var onDone: () -> Void
func makeUIViewController(context: Context) -> UINavigationController {
let preview = QLPreviewController()
preview.dataSource = context.coordinator
preview.navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .done,
target: context.coordinator,
action: #selector(Coordinator.done)
)
preview.navigationItem.leftBarButtonItem?.accessibilityIdentifier = "quick-look-done-button"
return UINavigationController(rootViewController: preview)
}
func updateUIViewController(_ controller: UINavigationController, context: Context) {
context.coordinator.onDone = onDone
guard context.coordinator.url != url as NSURL else { return }
context.coordinator.url = url as NSURL
(controller.viewControllers.first as? QLPreviewController)?.reloadData()
}
func makeCoordinator() -> Coordinator {
Coordinator(url: url as NSURL, onDone: onDone)
}
// MARK: - Coordinator
final class Coordinator: NSObject, QLPreviewControllerDataSource {
var url: NSURL
var onDone: () -> Void
init(url: NSURL, onDone: @escaping () -> Void) {
self.url = url
self.onDone = onDone
}
func numberOfPreviewItems(in controller: QLPreviewController) -> Int { 1 }
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
url
}
@objc func done() {
onDone()
}
}
}