我已经创建了一个测试应用程序来了解视图/视图控制器的工作方式以及如何在没有故事板或笔尖的情况下以编程方式在它们之间进行导航。
我基本上设置了一个名为Viewcontroller的rootViewController
,它在AppDelegate
中设置。
此视图在启动时显示view1,其中包含一个uibutton,它在rootViewController
中调用通知以呈现view2。但是,当我这样做时,我不断收到警告:
Warning: Attempt to present <View1: 0x7be66c80> on <ViewController: 0x7be62980> whose view is not in the window hierarchy!
我控制viewcontroller的代码如下:
#import "ViewController.h" #import "View1.h" #import "View2.h" @interface ViewController () @end @implementation ViewController -(void) loadView{ [super loadView]; } -(void)viewDidAppear:(BOOL)animated{ NSLog(@"View appeared"); [[NSNotificationCenter defaultCenter] removeObserver:self name:@"view1" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(view1:) name:@"view1" object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:@"view2" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(view2:) name:@"view2" object:nil]; [self showView1]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)view1:(NSNotification*) notification{ NSLog(@"Showing view1"); [self dismissViewControllerAnimated:YES completion:nil]; [self showView1]; } -(void)showView1{ dispatch_async(dispatch_get_main_queue(), ^{ [self.view.window.rootViewController presentViewController:[[View1 alloc]init] animated:YES completion:nil]; }); } -(void)view2:(NSNotification*) notification{ NSLog(@"Showing view2"); [self dismissViewControllerAnimated:YES completion:nil]; [self showView2]; } -(void)showView2{ dispatch_async(dispatch_get_main_queue(), ^{ [self presentViewController:[[View1 alloc]init] animated:YES completion:nil]; }); } @end
编辑:我忘了提到view1最初显示没有任何错误或问题。
编辑:view1和view2的代码完全相同,只是它们发送不同的通知:
#import "View1.h" @interface View1 () @end @implementation View1 - (void)loadView { [super loadView]; self.view.frame = [[UIApplication sharedApplication].keyWindow bounds]; // Do view setup here. UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button addTarget:self action:@selector(touchedLogin:) forControlEvents:UIControlEventTouchUpInside]; [button setTitle:@"Login" forState:UIControlStateNormal]; button.layer.cornerRadius=1; button.frame = CGRectMake(self.view.bounds.size.width/2-100, self.view.bounds.size.height-200, 200, 60.0); [button setTitleEdgeInsets:UIEdgeInsetsMake(5.0, 0.0, 0.0, 0.0)]; //[_window setBackgroundColor:[UIColor whiteColor]]; [self.view addSubview:button]; } -(void)touchedLogin:(id*)sender{ [[NSNotificationCenter defaultCenter] postNotificationName:@"view2" object:nil]; } @end
答案 0 :(得分:0)
您收到此错误是因为您正在使用animation
解除View1,然后立即调用showView2(实际上显示了View1,因为您在该方法中有[View1 alloc]init]
)。由于动画需要一些时间,因此当View1仍在屏幕上时,您尝试呈现View1,而不是ViewController
。一般来说,做出解雇和演示并不是一个好主意,一个接着就是这样。如果你在没有动画的情况下解雇,我认为它可能会起作用(虽然我从不这样做)。