从RootViewController调用函数

时间:2013-04-18 00:35:55

标签: objective-c

如何从RootViewController拨打FirstViewController功能? 我正在使用带有故事板的Xcode 4.6。


RootViewController.m:

-(void)openMenu
{
    ...
}

FirstViewController:

- (IBAction)btnMenu:(id)sender {
    RootViewController *root = [[RootViewController alloc] init];
    [root openMenu]; // No visible @interface for 'RootViewController' declares the selector 'openMenu'
}

2 个答案:

答案 0 :(得分:3)

您必须在标题RootViewController.h中声明该方法。实施例

- (void)openMenu;

答案 1 :(得分:1)

这种情况的常见做法是使用委托。您的FirstViewController会有一个委托,然后您的RootViewController会为该实例设置委托,并会收到该事件的信息。

<强> FirstViewController.h

@protocol FirstViewDelegate;

@interface FirstViewController : UIViewController

@property (strong) id<FirstViewDelegate> delegate;

@end

@protocol FirstViewDelegate <NSObject>

- (void)openMenu;

@end

<强> FirstViewController.m

- (IBAction)btnMenu:(id)sender {
    [self.delegate openMenu];
}

<强> MainViewController.h

#import "FirstViewController.h"

@interface RootViewController : UIViewController
<
FirstViewDelegate
>

<强> MainViewController.m

-(IBAction)showFirstViewButtonClicked:(id)sender {
    FirstViewController *firstViewController = [[FirstViewController alloc] init];
    firstViewController.delegate = self;
    [self presentViewController:firstViewController animated:YES completion:nil];
}

-(void)openMenu {
   // this will be called when the btnMenu action is fired in the firstViewController
}