问题
SwiftUI, macOS:
I'm trying to get a menu item to open "default PDF viewer of your choice", with a specific bundled PDF.
Here's what I have thus far:
import SwiftUI
import WebKit
import PDFKit
func Guide1(_ sender: Any) {
if let pdfURL = Bundle.main.url(forResource: "Guide1", withExtension: "pdf"){
if NSWorkspace.shared.open(pdfURL) {
}
}
}
func Guide2(_sender: Any) {
if let pdfURL = Bundle.main.url(forResource: "Guide2", withExtension: "pdf"){
if NSWorkspace.shared.open(pdfURL) {
}
}
}
Now, what I'm missing is how to call these functions.
From previous tutorials, I've found that one way of getting the menu items to "do something" is to ctrl-click and drag the Menu Item entry to First Responder, and then select functions from the list. However, these Guide1 + Guide2 functions are not displayed.
Other tutorials suggest using @IBAction
- but the minute I type that into a SwiftUI app, an error tells me to get the @IBaction
replaced with "nothing". So I cannot use those either.
So, are these even valid strings for opening a PDF - and if so, how do I connect a dropdown menu item so that these PDFs are opened?
回答1:
It needs to be added not in SwiftUI view but, for example and simplest, in AppDelegate as below
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBAction func Guide1(_ sender: Any) {
if let pdfURL = Bundle.main.url(forResource: "Guide1", withExtension: "pdf"){
if NSWorkspace.shared.open(pdfURL) {
}
}
}
then in your Main.storyboard (or XIB) just CTRL-drag from menu item to FirstResponder
and Guide1
action is there to bind (sometime build might be required before that, but as tested on Xcode 11.2 it just works).
来源:https://stackoverflow.com/questions/59805461/mapping-a-topbar-menu-item-in-swiftui-app-to-opening-a-specific-bundled-pdf