简体   繁体   English

Objective-C类

[英]Objective-C Classes

So I have a ViewController Class which is my first view, I then add a subview to it, pseudo code code below; 因此,我有一个ViewController类,这是我的第一个视图,然后向其添加一个子视图,下面是伪代码;

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. 我的问题是,在ViewController1中,我有一个执行动画并删除视图的方法。 How can I call that method from a button on ViewController 2? 如何从ViewController 2上的按钮调用该方法?

I tried doing something like in ViewController2... 我尝试在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. 这很有趣,因为在ViewController1的“后退”方法中,我有一个NSLog语句,它可以工作,但其他代码都不起作用。 So I know the method is getting called from my other class, but only the NSLog part of it executes? 所以我知道该方法正在从我的其他类中调用,但是只有它的NSLog部分可以执行? Any Suggestions. 有什么建议么。

SO basically I want to call a method of ViewController1 from ViewController2 所以基本上我想从ViewController2调用ViewController1的方法

You can't create a second instance of ViewController1 and get the effect you're looking for. 您无法创建ViewController1的第二个实例并获得所需的效果。 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. 在这种情况下,您可以通过在ViewController2中创建一个ivar来记住父对象是谁,并在添加另一个VC时对其进行分配来完成此操作。 Let's say you call the ivar owningViewController1. 假设您将ivar称为owneringViewController1。 Add a property for it in ViewController2.h and synthesize it at the top of ViewControler2.m, then change your example to: 在ViewController2.h中为其添加一个属性,并在ViewControler2.m的顶部对其进行合成,然后将示例更改为:

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: 然后,不必费心创建新的ViewController1实例,只需使用保存的实例即可:

[owningViewController1 back];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM