I currently use a QLPreviewController in a SwiftUI app with the help of UIViewControllerRepresentable to display a PDF.
This works well as the user can interact with the PDF using the keyboard to input data but also using PencilKit
I was wondering if there was a way to force resign the first responder within the QLPreviewController as the input could either be a text field with the keyboard or drawing with the PKToolPicker.
This is what I tried:
- I created this extension to find the key window based on this answer
extension UIApplication {
var keyWindow: UIWindow? {
// Get connected scenes
return self.connectedScenes
// Keep only active scenes, onscreen and visible to the user
.filter { $0.activationState == .foregroundActive }
// Keep only the first `UIWindowScene`
.first(where: { $0 is UIWindowScene })
// Get its associated windows
.flatMap({ $0 as? UIWindowScene })?.windows
// Finally, keep only the key window
.first(where: \.isKeyWindow)
}
}
- Then using this answer, I execute this line of code when tapping on a SwiftUI button:
UIApplication.shared.keyWindow?.endEditing(true)
However this doesn't seem to dismiss the keyboard nor the PKToolPicker
- I've even tried the below which I found on another answer:
extension UIApplication {
func endEditing() {
sendAction(#selector(UIResponder.resignFirstResponder),
to: nil,
from: nil,
for: nil)
}
}
And while this worked when on my login form when I wanted to dismiss the keyboard, this doesn't seem to work within the QLPreviewController
Is there any other way I can force resignFirstResponder or is there something similar to end editing for SwiftUI ?
