在Swift 4中创建类似Spotlight的窗口吗?

时间:2019-01-05 17:35:08

标签: swift xcode macos-mojave

我想创建一个窗口作为我的应用程序的一部分,该窗口在敲击特定的击键后显示类似于Spotlight的窗口。

enter image description here

但是我只能隐藏title

override func viewWillAppear() {
    self.view.window?.titleVisibility = .hidden
    self.view.window?.titlebarAppearsTransparent = true
    self.view.window?.styleMask.insert(.fullSizeContentView)
}

这将导致:

enter image description here

如何使用Xcode 10和Swift创建这样的视图?

1 个答案:

答案 0 :(得分:0)

您可以使用 NSPanel 创建自定义窗口

final class Panel: NSPanel {
    init(contentRect: NSRect, backing: NSWindow.BackingStoreType, defer flag: Bool) {
        super.init(contentRect: contentRect, styleMask: [.titled, .resizable, .closable, .fullSizeContentView], backing: backing, defer: flag)
        
        self.isFloatingPanel = true
        self.level = .floating
        self.collectionBehavior.insert(.fullScreenAuxiliary)
        self.titleVisibility = .hidden
        self.titlebarAppearsTransparent = true
        self.isMovableByWindowBackground = true
        self.isReleasedWhenClosed = false
        self.standardWindowButton(.closeButton)?.isHidden = true
        self.standardWindowButton(.miniaturizeButton)?.isHidden = true
        self.standardWindowButton(.zoomButton)?.isHidden = true
    }
    
    // `canBecomeKey` and `canBecomeMain` are required so that text inputs inside the panel can receive focus
    override var canBecomeKey: Bool {
        return true
    }
    
    override var canBecomeMain: Bool {
        return true
    }
}

并在 AppDelegate 中像这样使用它:

final class AppDelegate: NSObject, NSApplicationDelegate {
   lazy var panel: NSPanel = FloatingPanel(
        contentRect: NSRect(x: 0, y: 0, width: 700, height: 320),
        backing: .buffered,
        defer: false
    )

   func applicationDidFinishLaunching(_ aNotification: Notification) {
        // panel.contentView = ...
        panel.makeKeyAndOrderFront(nil)
        panel.center()
   }
}