如何从已经在UINavigationController堆栈上的UIViewController调用方法

时间:2013-06-06 20:53:11

标签: iphone ios objective-c delegates protocols

我在UINavigationStack上有一个UIViewController,从这个UIView我加载另一个视图不是在堆栈上而是作为子视图。我加载的这个视图只是我覆盖到正在显示的应用程序的首选项视图。

myViewController <- on the stack button touch loads as a subview to myViewController
+ prefrencesViewController 

我的问题是,有没有办法从prefrencesViewController调用myViewController中的方法?我正在尝试使用委托和协议,但它不起作用,所以我希望有一个简单的方法来做到这一点我还不知道或者我可以得到一些帮助我的委托/协议...

这是代码和协议设置的代码

// prefrencesViewController.h

@protocol GetPrefrencesViewControllerDelegate <NSObject>
-(void)reloadViewFromSavedPrefrences;
@end

//delegates and protocols
@property (nonatomic, weak) id <GetPrefrencesViewControllerDelegate> delegate;

// prefrencesViewController.m

//delegates and protocols
@synthesize delegate;

//.. inside button action
[[self delegate] reloadViewFromSavedPrefrences];

// myViewController.h

#import "prefrencesViewController.h"

@interface myViewController : UIViewController <UITabBarDelegate, GetGUIEncodedData, GetPrefrencesViewControllerDelegate> {

// prefrencesViewController set up
    prefrencesViewController *pvc;

@property (strong, nonatomic) prefrencesViewController *pvc;

// myViewontroller.h

@synthesize pvc;

- (void)viewDidLoad
{
    //..
    [pvc setDelegate:self];
}

//Delegate and prefrences.. Saved pressed reload the view here.
-(void)reloadViewFromSavedPrefrences {

    NSLog(@"WORKED");

}

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

我不确定你是否按照我将在下面介绍的步骤进行操作,但如果你不在这里就是例子。

<强> PresentedViewController.h

//import stuff
@protocol PresentedViewControllerDelegate <NSObject>
-(void)methodThatSouldBeImplementedByOtherController; //you can add params
@end

@interface PresentedViewController : UIViewController {
 //instance variables
}
@property (nonatomic, assign(week for ARK)) id<PresentedViewControllerDelegate>delegate
//public methods here

<强> PresentedViewController.m

@implementation PresentedViewController 
@synthesize delegate;

//method implementation here

-(IBAction)buttonThatWillCallTheDelegate:(id)sender {

   if([self.delegate respondsToSelector:@selector(methodThatSouldBeImplementedByOtherController)]) {
    [self.delegate methodThatSouldBeImplementedByOtherController];
   }
}

<强> ControllerThatWillPresent.h

@interface ControllerThatWillPresent : UIViewController <PresentedViewControllerDelegate> {
   //instance variables
}

//some methods maybe

<强> ControllerThatWillPresen.m

@implementation ControllerThatWillPresen 

-(void)methodThatWillShowTheVC {
     PresentedViewController *vc = [PresentedViewController alloc] init]; //initWithNibname...
    vc.delegate = self;
   //presentVc, pushVc, addChild ... 
}

-(void)methodThatSouldBeImplementedByOtherController {
 //do stuff in delegate method
}