从iphone的不同视图控制器调用功能

时间:2010-03-05 18:22:29

标签: iphone objective-c function uiviewcontroller call

我有一个问题,我想调用另一个控制器在一个视图控制器中定义的函数。 我尝试了似乎只有一百种不同的设置,似乎没什么用。

我发布了基本代码,并希望有人能告诉我他们将如何做到这一点。 基本上我想做的就是调用SwitchViewController中定义的MYBPress函数 按下dealB按钮时的GameViewController。任何帮助将不胜感激。 PS:我已经编写了很长时间,但对于Obj-C来说它是新的

// ------- SwitchViewController.h  ---------------
#import <UIKit/UIKit.h>
@class GameViewController;
@class OptionsViewController;

@interface SwitchViewController : UIViewController {
 OptionsViewController *optionsViewController;
}  

@property ( retain, nonatomic ) OptionsViewController *optionsViewController;
@property ( retain, nonatomic ) GameViewController *gameViewController;
-(IBAction)MyBPress:(id)sender;
@end


//  --------  GameViewController.h ------------

#import <UIKit/UIKit.h>

@interface GameViewController : UIViewController {
   IBOutlet UIButton    *dealB; 
}
@property(nonatomic,retain) IBOutlet UIButton    *dealB;
- (IBAction)dealB:(id)sender;
@end


//  -------  GameViewController.m
#import "GameViewController.h"

@implementation GameViewController
@synthesize dealB;          // The Deal button

- (IBAction)dealB:(id)sender
{
   //  Here is where I want to call the MyBPress function
}

@end

3 个答案:

答案 0 :(得分:25)

/* Ok, so based on a suggestion to use Notifications, I solved my problem.  It's
actually so simple, it ridiculous I had so much trouble with it.   Thought I'd 
post it just in case some other newbie hits the same type issue.
*/

// in the SwitchViewController.m  I added this.  This sets it up so 
// when the dealNotification
// is triggered, the HideBar function I have defined in SwitchViewController 
// gets called.
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(HideBar) name:@"dealNotification" object: nil];


// in the GameViewController.m where I want to call the function in the other controller,
// I added this and it send the notification to run the function
[[NSNotificationCenter defaultCenter] postNotificationName:@"dealNotification" object: nil];

答案 1 :(得分:5)

“大家好,我有一个问题,我想从另一个控制器调用一个视图控制器中定义的函数。我尝试看似似乎有一百个不同的设置,似乎没有任何工作。”

这是因为它设计不好。控制器不应直接相互通信。

您应该考虑使用代理,通知或某些共享的中央实体。

答案 2 :(得分:1)

为什么不让按钮直接将两个消息发送到各自的控制器? UIButton的实例本身就能够向多个目标发送多条消息。要配置按钮,您可以根据需要多次发送以下消息:

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents

您也可以在Interface Builder中连接按钮以执行相同的操作。或者混合搭配你的内心。