Benjamin Sherstinsky
Benjamin Sherstinsky

Reputation: 31

How do you navigate between views in a Cocoa application using Swift?

I am trying to use NSView to navigate between NSViewControllers using Swift in an OS X application.

Upvotes: 3

Views: 3126

Answers (2)

john elemans
john elemans

Reputation: 2676

First create a custom view in your xib file. This will be where the various view controllers will put their own views. In your the code which will navigate between the view controllers create a variable to reference the custom view in your xib file;

    var masterView : NSView!

Back in interface builder, connect the custom view to your variable. masterView now refers to the custom view and gives you the means to change it.

You can replace that view with the view of the view controller that you want to be active at any given time. For this example, assume that I have three view controllers (as examples);

    var pDemog : patientDemographicsController!
    var pExams : patientExamsListController!
    var pReports : patentReportsViewController!

The first view controller can be set up as follows;

    masterView.addSubview(pDemog.view)

Later when needed you can replace the view with the view of a different view controller

    masterView.replaceSubview(pDemog!.view with: pExams!.view)

and back again;

    masterView.replaceSubview(pExams!.view with: pDemog!.view)

or to another;

    masterView.replaceSubview(pExams!.view with: pReports!.view)

That's the mechanism for changing the view. You can add animations as referenced above, but it's not necessary. Also, you should prepare the views in the view controllers as follows; (this is just one example, you need it for each view controller)

    pDemog.view.setFrameOrigin(NSPoint(x:0, y:0))
    pDemog.view.setFrameSize(masterView.frame.size)

do this before you start setting the views in the masterView.

Upvotes: 2

Suhas Aithal
Suhas Aithal

Reputation: 852

I am not sure what are you trying to ask here. I would suggest to go through these links

Mac OS X Cocoa multiview application navigation

Easy Switching of "View Controllers" in Mac Apps (similar to iOS)

Hope this helps,cheers.

Edit:

If you are new to swift i would suggest to go through https://developer.apple.com/swift/ first. Your methods will look like the following in swift

func switchSubViews(newSubview : NSView) {
//Implementation
}

func prepareViews(){
//Implementation
}

Upvotes: 2

Related Questions