5

我有一个问题,我想从另一个控制器调用一个视图控制器中定义的函数。我尝试了一百种不同的设置,但似乎没有任何效果。

我已经发布了基本代码,希望有人能告诉我他们会怎么做。基本上,我要做的就是在按下 dealB 按钮时从 GameViewController 调用 SwitchViewController 中定义的 MYBPress 函数。任何帮助将不胜感激。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
4

3 回答 3

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];
于 2010-03-05T20:51:59.563 回答
5

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

这是因为它是糟糕的设计。控制器不应直接相互交谈。

你应该考虑使用委托、通知或一些共享的中心实体。

于 2010-03-05T18:52:01.220 回答
1

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

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

你也可以在 Interface Builder 中连接按钮来做同样的事情。或者混合搭配你的内心满足感。

于 2010-03-05T20:21:53.827 回答