Mapping a Topbar Menu Item in SwiftUI app to opening a specific bundled PDF?

∥☆過路亽.° 提交于 2021-01-27 14:11:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!