Keep window always on top?

后端 未结 3 1116
眼角桃花
眼角桃花 2020-11-29 01:45

In Objective-C for Cocoa Apps it\'s possible to use such way to keep window always on top?

How to achieve the same with Swift?

self.view.window?.leve         


        
3条回答
  •  心在旅途
    2020-11-29 02:41

    While the other answers are technically correct - when your app will or did resigns active, setting the window level to .floating will have no effect.

    .floating means on top of all the windows from the app you are working on, it means not on top of all apps windows.

    Yes there are other levels available you could set, like kCGDesktopWindowLevel which you can and should not set in swift to make your window float above all.

    None of them will change the fact that your window will go behind the focused and active apps window. To circumvent i chose to observe if the app resigns active notification and act accordingly.

    var observer : Any;
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        observer = NotificationCenter.default.addObserver(
            forName: NSApplication.didResignActiveNotification, 
            object: nil, 
            queue: OperationQueue.main ) { (note) in
    
            self.view.window?.level = .floating;
    
            // you can also make your users hate you, to take care, don't use them.
            //NSApplication.shared.activate(ignoringOtherApps: true)
            //self.view.window?.orderFrontRegardless();
        }
    }
    

    another way could be subclassing NSWindow and override the property .level with an always returning .floating, but the code above is less work and keeps control in the place where you want to set the window floating.

提交回复
热议问题