How to bring NSWindow to front and to the current Space?

SwiftCocoa

Swift Problem Overview


I'm using this code to bring up my window:

[self.window makeKeyAndOrderFront:self];
[self.window setOrderedIndex:0];

But often it will be beneath other windows or displayed in other Space desktop that I last open it in. How do I make it always appear "in front" to the user?

Update I found the answer from previously asked question; make the window show up to the top of other windows: [NSApp activateIgnoringOtherApps:YES];

But how to move the app to the user's current Space?

Swift Solutions


Solution 1 - Swift

To bring your app to the front:

[NSApp activateIgnoringOtherApps:YES];

Swift:

NSApp.activateIgnoringOtherApps(true)

Swift 3:

NSApp.activate(ignoringOtherApps: true)

Solution 2 - Swift

Perhaps you want:

  [self.window setCollectionBehavior: NSWindowCollectionBehaviorCanJoinAllSpaces];

Experiment with the other collection behaviors... I found NSWindowCollectionBehaviorMoveToActiveSpace was a bit buggy in 10.5 but it might be better now.

Solution 3 - Swift

The syntax seems to be a little different with Swift 2:

NSApplication.sharedApplication().activateIgnoringOtherApps(true)

Solution 4 - Swift

Swift 5.0 +

 NSWindow.orderFrontRegardless()

Solution 5 - Swift

> But how to move the app to the user's current Space?

You don't. Spaces hold windows, not applications. (That's why the collectionBehavior property is on NSWindow, not NSApplication.)

Solution 6 - Swift

Swift 3.0

NSApp.activate(ignoringOtherApps: true)

Solution 7 - Swift

If you want to your app to come to the front, even if its minimised and have it activated (given active focus), then use both of these:

			NSApp.activate(ignoringOtherApps: true)
			NSApp.windows.first?.orderFrontRegardless()

If you only want to bring it to the front, without giving it focus, just use:

			NSApp.windows.first?.orderFrontRegardless()

Solution 8 - Swift

Swift 2.0

NSApp.activateIgnoringOtherApps(true)

Helpful Programming Tips and Hacks

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTeo Choong PingView Question on Stackoverflow
Solution 1 - SwiftjtbandesView Answer on Stackoverflow
Solution 2 - SwiftNicholas RileyView Answer on Stackoverflow
Solution 3 - SwiftiphaawView Answer on Stackoverflow
Solution 4 - SwiftarthasView Answer on Stackoverflow
Solution 5 - SwiftPeter HoseyView Answer on Stackoverflow
Solution 6 - SwiftCeeView Answer on Stackoverflow
Solution 7 - SwiftAdamView Answer on Stackoverflow
Solution 8 - SwiftquemefulView Answer on Stackoverflow