So I have a ViewController Class which is my first view, I then add a subview to it, pseudo code code below;
ViewController2 *viewController2 = [[ViewController2 alloc] init];
[self addSubview:viewController2.view];
My question is, in ViewController1, I have a method that does an animation and removes the view. How can I call that method from a button on ViewController 2?
I tried doing something like in ViewController2...
ViewController1 *viewController1 = [[ViewController1 alloc] init];
[viewController1 back]; //Trying to call method in other class from ViewController2
And its funny because in the "back" method on ViewController1,I have an NSLog statement, and it works, but none of the other code works. So I know the method is getting called from my other class, but only the NSLog part of it executes? Any Suggestions.
SO basically I want to call a me开发者_JAVA百科thod of ViewController1 from ViewController2
You can't create a second instance of ViewController1 and get the effect you're looking for. You need to call it on the instance that has already been created.
In this case, you can accomplish it by creating an ivar in ViewController2 to remember who the parent is and assign it when you add in the other VC. Let's say you call the ivar owningViewController1. Add a property for it in ViewController2.h and synthesize it at the top of ViewControler2.m, then change your example to:
ViewController2 *viewController2 = [[ViewController2 alloc] init];
[self addSubview:viewController2.view];
[viewController2 setOwningViewController1:self];
Then, don't bother creating a new ViewController1 instance, just use the one saved:
[owningViewController1 back];
精彩评论