Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep window always on the top with Swift? [duplicate]

Tags:

swift

I just create a new application project

  • Xcode Version 7.3 (7D175)
  • Swift Version 2.2
  • Mac OS version OS X El Capitan 10.11.4

I want to make a desktop app for Mac OS and I had set the window level but it's not work.

like image 592
Steve Jiang Avatar asked Aug 02 '16 03:08

Steve Jiang


3 Answers

Making your app always on top of the other applications in Swift 5 is so simple.

override func viewDidAppear() {
    view.window?.level = .floating
}
like image 194
Esmaeil MIRZAEE Avatar answered Nov 10 '22 23:11

Esmaeil MIRZAEE


You need check window != nil before any custom code

class ViewController: NSViewController {
    var addedObserver = false

    override func viewDidLoad() {
        super.viewDidLoad()

        if let window = self.view.window {
            // custom window here
            window.level = Int(CGWindowLevelForKey(.FloatingWindowLevelKey))
        } else {
            addedObserver = true
            self.addObserver(self, forKeyPath: "view.window", options: [.New, .Initial], context: nil)
        }
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if let window = self.view.window {
            // custom window here
            window.level = Int(CGWindowLevelForKey(.FloatingWindowLevelKey))
        }
    }

    deinit {
        if addedObserver {
            self.removeObserver(self, forKeyPath: "view.window")
        }
    }
}
like image 28
larva Avatar answered Nov 10 '22 23:11

larva


Still testing it, but this is Larva's answer in Swift 4 and it seems to be working.

var observingFloat = false

 override func viewDidLoad() {
        super.viewDidLoad()
        self.view.wantsLayer = true

        if self.view.window != nil {
            NSApplication.shared.windows.first?.level = NSWindow.Level(rawValue: 1)
        } else {
            observingFloat = true
            self.addObserver(self, forKeyPath: "view.window", options: [.new, .initial], context: nil)
        }
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        if self.view.window != nil {
            NSApplication.shared.windows.first?.level = NSWindow.Level(rawValue: 1)
        }
    }
like image 24
Dave Levy Avatar answered Nov 11 '22 00:11

Dave Levy