//
// MyGameViewController.h // #import < UIKit/UIKit.h > #import "SecondViewController.h"@interface MyGameViewController : UIViewContro开发者_如何学Cller {
IBOutlet SecondViewController *secondViewController; } -(IBAction)goToSecondView; @end
//
// MyGameViewController.m // #import "MyGameViewController.h"@implementation MyGameViewController
-(IBAction)goToSecondView{
[self presentModalViewController:secondViewController animated:YES]; }
//
// MyGameView.h // #import < UIKit/UIKit.h > #import "Sprite.h"@interface MyGameView : UIView {…}
Currently I have implemented a button on the MyGameView.xib to invoke the secondViewController view and it works. But I want the secondViewController get invoked by programming inside MyGameView.m when there is interruption, not by pressing a button. Therefore, I think there are 2 approaches:
a) Either make the goToSecondView method available to MyGameView.m
b) Implement all the code in MyGameViewController.h and MyGameViewController.m to MyGameView.m.Issues:
1) When tried to make a) happen, I have to make goToSecondView method starting with (void), not (IBAction). But then how to invoke it in MyGameView.m? 2) I tried to do b) and implemented all code to MyGameView.m. But presentModalViewController is a method of ViewController and does not work in UIView. So what is the solution?As you stated, you can't call presentModalViewController in a UIView class. This seems like a great opportunity to use a delegate. You could do something along the lines of:
In MyGameView.h
@protocol MyGameViewDelegate
- (void)showSecondView;
@end
@interface MyGameView {
}
@property (nonatomic, assign) id <MyGameViewDelegate> delegate;
...
@end
In MyGameView.m, when you need to show the second view:
[self.delegate showSecondView];
In MyGameViewController.h:
#import "MyGameView.h"
@interface MyGameViewController : UIViewController <MyGameViewDelegate> {
...
In MyGameViewController.m:
#pragma mark MyGameViewDelegate methods
- (void)showSecondView {
[self goToSecondView];
}
Note that you'll also need to set MyGameViewController to be the delegate of MyGameView. You could do that in Interface Builder, or in code, depending on where you create the two objects.
To do it in code, for example in the MyGameViewController.h viewDidLoad method:
myGameView.delegate = self;
精彩评论