我有一个UIViewController它显示不同的UIViewController子类。在主UIViewController中。m,我有一个名为"Home"的子类加载在应用程序启动。
现在,在Home视图加载,我有一个按钮,我想用它来切换到另一个名为'PreGameInfo'的视图。我正在尝试使用下面的代码:
- (IBAction)showPreGameInfo:(id)sender {
[self.view insertSubview:preGameInfo.view atIndex:0];
}
它不起作用,我知道这是因为"自我"。view'需要引用主UIViewController而不是Home视图的self。有人知道如何插入到主UIViewController当使用一个UIButton,而在子视图??
谢谢!
您可以使用委托。这很简单
在信息视图控制器中实现这个;
在InformationViewController.h
@protocol InformationViewControllerDelegate;
@interface InformationViewController : UIViewController {
id <InformationViewControllerDelegate> delegate;
}
@property (nonatomic, assign) id <InformationViewControllerDelegate> delegate;
- (IBAction)returnBack:(id)sender;
@end
@protocol InformationViewControllerDelegate
- (void)InformationViewControllerDidFinish:(InformationViewController *)controller;
@end
在InformationViewController.m
- (IBAction)returnBack:(id)sender {
[self.delegate InformationViewControllerDidFinish:self];
}
在任何你需要的视图控制器中使用委托,像这样:
在HomeViewController.h
#import "InformationViewController.h"
@interface HomeViewController : UIViewController <InformationViewControllerDelegate> {
}
编写将视图从Home视图更改为Information视图的方法
- (IBAction)goToInformationView:(id)sender;
在HomeViewController.m
- (IBAction)goToInformationView:(id)sender {
InformationViewController *controller = [[InformationViewController alloc] initWithNibName:nil bundle:nil];
controller.delegate = self;
// You can chose the transition you want here (they are 4 see UIModalTransitionStyle)
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];
[controller release];
}
最后但并非最不重要的是委托方法它在InformationViewController完成时通知HomeViewController
- (void)InformationViewControllerDidFinish:(InformationViewController *)controller {
[self dismissModalViewControllerAnimated:YES];
}
希望能有所帮助
- (IBAction)showPreGameInfo:(id)sender {
[superview insertSubview:preGameInfo.view atIndex:0];
}
这段代码可以工作吗?
[self.parentViewController.view addSubview:myView];
在modalView中做:
[self presentModalViewController:preGameInfo animated:YES]
或者你可以这样做…
这一行将把你的新视图添加到windows rootViewControllers视图
[self.view.window.rootViewController.view addSubview:preGameInfo.view];