9

What would be the OS X equivalent of ios' (Ruby style) :

@window.rootViewController = NSViewController.alloc.initWithNibName(nil, bundle: nil)

There are two aspects :

  • dealing with the absence of rootViewController in os x
  • doing the equivalent of initWithNibName(nil, bundle: nil), that fails on os x

I'm trying to build a window in code (without nib)... and follow along Pragmatic's Programmer Guide to RubyMotion (written for iOS).

MichaelC
  • 357
  • 2
  • 12

3 Answers3

10

In my case, I had a single view controller owned by the window, so the following code worked for me:

let viewController = NSApplication.sharedApplication().keyWindow!.contentViewController as! MyViewController

where MyViewController is my NSViewController subclass.

Senseful
  • 86,719
  • 67
  • 308
  • 465
  • this worked for me despite having multiple viewControllers - I simply checked that the `contentViewController` was able to be downcast to the correct subclass before grabbing what I needed from it – Brickers Feb 21 '18 at 21:15
3

There is no concept of a "rootViewController" in OS X applications. This is because applications are made up of one or more windows and/or a menu bar, none of which is the "root".

You can, however, find the window controller starting from a view controller:

[[[self view] window] delegate];

If you are looking to call custom methods on the window controller, it is probably better to create a delegate so that assumptions about the controller don't get you into trouble.

The equivalent of NSViewController.alloc.initWithNibName(nil, bundle: nil) would be:

[[NSViewController alloc] initWithNibName:nil bundle:nil];

Method calls get nested in square brackets, methods with multiple parameters are simply label1:parameter1 label2:parameter2...

Usually, though, you would have a custom NSViewController subclass that you would instantiate instead.

Community
  • 1
  • 1
BergQuester
  • 6,167
  • 27
  • 39
2

If you want to reset rootViewController like in iOS you can use this code:

let storyBoard = NSStoryboard(name: NSStoryboard.Name(rawValue:"Main"), bundle: Bundle.main)
let homeViewController = storyBoard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "SIHome")) as! HomeViewController
NSApp.keyWindow?.contentViewController = homeViewController
  • NSApp is a shortcut for NSApplication.shared()
  • rootViewController is called contentViewController in OSX
Heo Đất Hades
  • 1,573
  • 18
  • 14