【问题标题】:Create Spotlight-like window in Swift 4?在 Swift 4 中创建类似 Spotlight 的窗口?
【发布时间】:2019-05-31 22:37:00
【问题描述】:

我想创建一个窗口作为我的应用程序的一部分,该窗口在按下某个键后会显示类似 Spotlight 的窗口。

但我得到的只是隐藏title

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

结果:

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

【问题讨论】:

  • 我为我的一个应用程序中的一个类似窗口创建了一个库 - OpenQuickly,您可能会发现它有用。

标签: swift xcode macos-mojave


【解决方案1】:

您可以使用 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()
   }
}

【讨论】:

    猜你喜欢
    • 2011-06-30
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 2015-04-30
    • 2012-05-18
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    相关资源
    最近更新 更多