如何使用Objective C调用父Viewcontroller到子Viewcontroller方法?

时间:2016-01-19 12:52:33

标签: ios objective-c uiviewcontroller

我在mainviewcontroller中有一个按钮,当点击该按钮时,我想在另一个视图控制器上调用一个方法。下面的图片显示了我的方案,Green按钮单击以调用预览控制器VC1收到的方法,但没有navigation任何内容。我只需要调用那个方法!

enter image description here

2 个答案:

答案 0 :(得分:0)

  • 在VC1的.h文件中声明一个方法,并在VC1的.m文件中实现
  • 从MainView Controller调用该方法,
  • 在MainView Controller中创建NSNotificationObserver并在MainView Controller的.m文件中实现,

现在调用VC1的方法并返回之前,从VC1触发PostNotification并在MainView Controller中传递你想要的参数。

答案 1 :(得分:0)

@RobAu给出了正确的答案,因为您可以使用NSNotificationObserver并从任何地方拨打电话。

我使用的其他替代方案是使用协议,非常简单。

只需在子控制器中声明一个协议。启动视图时将父控制器作为委托。现在从子控制器的任何地方调用委托方法

以下是我使用的示例(在我的情况下,所有子控制器都是同类型的)

//ChildClass.h file of child class

@protocol updateIndex <NSObject>
    -(void)updateMediaId:(NSString*)currentMediaId;
@end

@interface ChildClass : UIViewController
    @property NSString *imageID;
    @property id updateIndexDelegate;
@end

//ChildClass.m file for child class where you want to call the delegate method

(我在viewDidAppear方法中调用)

-(void)viewDidAppear:(BOOL)animated{
    [self.updateIndexDelegate updateMediaId:_imageID];
}

在父类的ParentClass.m文件中,使用委托自己像这样

ChildClass *childObject = [[ChildClass alloc] init];
childObject.delegate = self;

并像这样定义委托方法

-(void)updateMediaId:(NSString*)currentMediaId {
    NSLog(@"%@",currentMediaId);
}

享受编码