Fred Wu
Fred Wu

Reputation: 928

How to control instance in another view controller

I'm new to Swift and OS X programming.

I am creating a desktop application with two view controllers, which are in a split view controller. How can I get access to the instances in another controller and change its attributes?

An example:

We have a drawing application, one view is canvas, the other is tools. There is a 'clear' button in tool view, how to set the canvas clear when click on this button?

Upvotes: 0

Views: 118

Answers (2)

Alfred
Alfred

Reputation: 161

You can try to use singleton pattern in your code. When you create the view controller, put the var out of the class like:

var fooViewController = FooViewController(...)

class FooViewController{
...
}

Then you can use the fooViewController anywhere in your project.

If you are working with storyboard, you can try some code like this:

var story = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
var view:MainTabViewController = story.instantiateViewControllerWithIdentifier("MainTab") as MainTabViewController

Hope this can be helpful.

Upvotes: 1

user3766624
user3766624

Reputation: 1

You can use delegates and protocols! Link to Official Apple Documentation

Heres a quick example:

protocol toolsProtocol {
    func pressedClear()
}
var delegate : toolsProtocol

In your canvas class

class Canvas: UIViewController, toolsProtocol {
    Tools.delegate = self
    func pressedClear() {
       // Insert stuff happens here
    }
}

Upvotes: 0

Related Questions