How to Set Window Level in Swift

How to keep window always on the top with Swift?

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")
}
}
}

NSWindow and setLevel, cant' get on top functionality working

Found an answer.
Two windows at the same place with different levels.

It's possible to create an invisible window with window level kCGBaseWindowLevelKey and put it right below the window with kCGScreenSaverWindowLevelKey level. Two windows at the same place with different levels.

- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSWindowStyleMask)windowStyle backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation
{
if (self = [super initWithContentRect:contentRect styleMask:NSWindowStyleMaskBorderless backing:NSBackingStoreBuffered defer:NO])
{
[self setBackgroundColor:[NSColor clearColor]];
}

return self;
}

Keep window always on top?

To change the window level you can't do it inside viewDidload because view's window property will always be nil there but it can be done overriding viewDidAppear method or any other method that runs after view is installed in a window (do not use it inside viewDidLoad):

Swift 4 or later

override func viewDidAppear() {
super.viewDidAppear()
view.window?.level = .floating
}

For older Swift syntax check the edit history

How to set window level in Swift

Following through the chain of defines:

#define NSScreenSaverWindowLevel     kCGScreenSaverWindowLevel

and...

#define kCGScreenSaverWindowLevel     CGWindowLevelForKey(kCGScreenSaverWindowLevelKey)   /* 1000 */

I think the corrected answer is:

window.level = Int(CGWindowLevelForKey(Int32(kCGScreenSaverWindowLevelKey)))

much casting because of discrepancies in enum types

How to hide Keyboard which is in another window? Swift

First, get a reference to host app keyWindow

  func getHostKeyWindow() -> UIWindow? {
if #available(iOS 13, *) {
return windows.first { $0.isKeyWindow }
} else {
return keyWindow
}
}

And then simply make endEditing as true

UIApplication.shared.getHostKeyWindow()?.endEditing(true)

It should close the keyboard in the window for which you have the reference!

Window visible on all spaces (including other fullscreen apps)

If you want a window to be visible on top of other fullscreen windows (in spaces), you should make an agent (accessory) application.
You can do it by setting LSUIElement key in the application’s Info.plist to 1 (YES)

If you still need a regular application you can do following:

  1. Create a separate agent (helper) application inside your main application bundle which will show your window. (There are plenty of good examples on how you can create such application)

  2. Play with NSApplicationActivationPolicy. You can try to change application's activation policy during a runtime.
    Swift 3:

    • NSApp.setActivationPolicy(.accessory) switch to agent(accessory)
    • NSApp.setActivationPolicy(.regular) switch to ordinary application

Keep in mind that .accessory policy hides the icon from Dock and you still need the code you have already:

window.collectionBehavior = .canJoinAllSpaces
window.level = Int(CGWindowLevelForKey(.floatingWindow))

How do I keep newly added UIWindow on top

Take a look at makeKeyAndVisible API

func makeKeyAndVisible()

Shows the window and makes it the key window.

This is a convenience method to show the current window and position it in front of all other windows at the same level or lower. If you only want to show the window, change its isHidden property to false.

Also, UIApplication has .windows property, which is an array of visible and hidden windows

var windows: [UIWindow]

You can iterate this array and find a window which you are gonna to set as a key window.

And lastly take a look at .windowLevel UIWindow property, it manages position of the window in the z-axis.

var windowLevel: UIWindow.Level { get set }

Window levels provide a relative grouping of windows along the z-axis. All windows assigned to the same window level appear in front of (or behind) all windows assigned to a different window level. The ordering of windows within a given window level is not guaranteed.

The default value of this property is normal. For a list of other possible window levels, see UIWindow.Level.

How can I programmatically display a window on a specific screen (i.e., main display as opposed to external displays) in Swift 5? [MacOS; Xcode 15]

Thanks to the question asked by @Willeke, I was able to use the following code to display the window on the main screen (as opposed to external displays). I just needed to use DispatchQueue.main.async {}.

   override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.async {

//set up the main display as the display where window shows up
let screens = NSScreen.screens
var pos = NSPoint()
pos.x = screens[0].visibleFrame.midX
pos.y = screens[0].visibleFrame.midY
self.view.window?.setFrameOrigin(pos)

}
}

Why does my NSWindow not float above full screen apps when created programmatically? (Swift 5)

7 months later and I managed to get it working by changing the window's styleMask to borderless

window.styleMask = [.borderless]

Better late then never I suppose...



Related Topics



Leave a reply



Submit