从一个视图控制器调用另一个视图控制器的方法

4
我在OneViewController.h中声明了一个名为"someMethod"的方法。
@interface OneViewController
{
UIView *tempView;
..

}
-(void) someMethod ;
@end

并在 OneViewController.m 文件中实现

@implementation OneViewController

-(void) someMethod 
{
tempView = [[UIView alloc]initWithFrame:CGRectMake(100, 50, 200, 250)];
tempView.backgroundColor = [UIColor yellowColor];
if([[self.view subviews] containsObject:tempView])
[tempView removeFromSuperView];
   else
   [self.view addsubview:tempView];

}

我想在不同的视图控制器 - secondViewController 中调用someMethod方法(类似于[OneViewController someMethod]),这样当我回到OneViewController时,可以看到someMethod所做的更改。

我需要使用appDelegate方法吗?

我尝试了以下方法,但它不起作用。

neViewController *newViewController = [[OneViewController alloc] init];
[newViewController someMethod];

感谢您提前的任何帮助。
谢谢。

你是从OneViewController跳转到SecondViewController吗?并且想要在SecondViewController中访问OneViewController的方法,对吗? - SriPriya
是的。我正在从OneViewController转移到SecondViewController,并希望从SecondViewController访问OneViewController方法。 - alekhine
4个回答

4
在SecondViewController中,声明一个OneViewController类的引用。您可以拥有分配属性。在移动到SecondViewController之前设置引用。现在,使用引用,您可以调用实例方法[_oneView someMethod]
OneViewController *_oneView;

同时添加assign属性,
@property(nonatomic,assign) OneViewController *_oneView;

在 .m 文件中合成变量。

当从 OneViewController 显示 SecondViewController 时,只需添加以下行。

secondView._oneView = self;

谢谢您的回复,Lanc。但是我如何在SecondViewController中创建对OneViewController的引用? - alekhine
非常感谢Lanc。它完美地运行了(我不知道为什么)....!!! 我需要详细研究传递引用和委托方法。 - alekhine

2
有时候直接调用方法创建 [classObject methodName] 不会反映视图中的更改。比如,如果你想将一个 UIScrollView 属性从 scrollEnble = NO; 更改为 scrollEnable = YES;,它不会反映出来。 你应该使用 UIApplication 的单例。
假设你想在 ViewController2 中调用 ViewController1' 的方法 - (void)myMethod,那么以下是具体步骤:
  • AppDelegate 中导入 ViewController1 并创建其对象 *vc。声明属性 @property (strong, nonatomic) ViewController1 *vc;,同时也进行 synthesize
  • 现在来到 Viewcontroller1 类中。在你的 Viewcontroller1viewDidLoad 中写如下代码:

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.vc1 = self;

  • 去到你的 ViewController2.h 并导入 AppDelegate.h
  • 在你想要调用 ViewController2 方法的地方写如下代码:

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [[appDelegate vc1] myMethod]; // to allow scrolling


1
理想情况下,您应该创建一个协议和委托方法来实现您所需要的功能。
在 secondViewController 中实现该协议,并将协议委托设置为 firstViewController,然后使用委托方法调用 secondViewController 中相关的方法。
希望这对您有帮助..!!

-1
一种方法是将声明更改为+(void) someMethod;在你的OneViewController.h文件中,并在实现文件中相应地将减号改为加号。这将使它成为一个类方法而不是实例方法。然后,在你的SecondViewController.m文件中,在实现声明之前确保放置@class OneViewController;;然后你可以调用[OneViewController someMethod],它应该会执行。干杯!

将符号从-更改为+会在编译时出错,显示实例变量在类方法中被访问。 - alekhine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接