Reputation: 609
So I am trying to perform a segue as soon as the window loads without having to click a button or have any action performed. The segue's are linked from a view controller, but not linked from the window controller because I can only get one segue to link from the Windowcontroller at a time. I tried this code in both "windowWillLoad" and "windowDidLoad" directly, and with it's own function. It isn't making the transition. Does it always have to be activated with a button? Can I not use segue's that aren't linked directly to the WindowController itself? I basically want to be able to choose between two different view controllers on the launch of the cocoa mac app.
import Cocoa
class WindowOne: NSWindowController {
var i = 0
override func windowWillLoad() {
}
override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) {
if i == 0 {
performSegueWithIdentifier("segone", sender: self)
} else {
performSegueWithIdentifier("segtwo", sender: self)
}
}
override func windowDidLoad() {
super.windowDidLoad()
}
}
Upvotes: 0
Views: 275
Reputation: 226
The problem here is that the segue cannot be performed until the window has actually appeared - and at the point that windowDidLoad
gets called it hasn't.
In iOS land we would handle this by calling performSegueWithIdentifier
in the viewDidAppear
method.
Here there are two options, as per this answer: viewWillAppear or viewDidAppear on NSWindowController
Either override the showWindow
method:
import AppKit
class WindowOne: NSWindowController {
var i = 1
override func showWindow(_ sender: Any?) {
super.showWindow(sender)
if i == 0 {
performSegueWithIdentifier("segone", sender: self)
} else {
performSegueWithIdentifier("segtwo", sender: self)
}
}
}
Or for more fine-grained behaviour one might catch NSWindowDelegate
calls. For example if you wanted the segue to occur whenever the window comes to the foreground you might implement windowDidBecomeKey
:
import AppKit
class WindowOne: NSWindowController, NSWindowDelegate {
var i = 1
override func windowDidLoad() {
super.windowDidLoad()
self.window?.delegate = self
}
func windowDidBecomeKey(_ notification: Notification) {
if i == 0 {
performSegueWithIdentifier("segone", sender: self)
} else {
performSegueWithIdentifier("segtwo", sender: self)
}
}
}
Upvotes: 1