【发布时间】:2015-03-30 02:37:02
【问题描述】:
我创建了一个测试应用程序来了解视图/视图控制器的工作原理以及如何在没有情节提要或 nib 的情况下以编程方式在它们之间导航。
我基本上设置了一个名为 Viewcontroller 的rootViewController,它设置在AppDelegate 中。
此视图在启动时显示 view1,其中包含一个 uibutton,该按钮调用rootViewController 中的通知以显示 view2。但是,当我这样做时,我不断收到警告:
Warning: Attempt to present <View1: 0x7be66c80> on <ViewController: 0x7be62980> whose view is not in the window hierarchy!
我的控制视图控制器代码如下:
#import "ViewController.h" #import "View1.h" #import "View2.h" @interface 视图控制器 () @结尾 @implementation 视图控制器 -(无效)加载视图{ [超级负载视图]; } -(void)viewDidAppear:(BOOL)动画{ NSLog(@"视图出现"); [[NSNotificationCenter defaultCenter] removeObserver:self name:@"view1" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self 选择器:@selector(view1:) name:@"view1" object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:@"view2" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self 选择器:@selector(view2:) name:@"view2" object:nil]; [自我展示视图1]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // 处理所有可以重新创建的资源。 } -(void)view1:(NSNotification*) 通知{ NSLog(@"显示view1"); [自我dismissViewControllerAnimated:是完成:无]; [自我展示视图1]; } -(无效)showView1{ dispatch_async(dispatch_get_main_queue(), ^{ [self.view.window.rootViewController presentViewController:[[View1 alloc]init] 动画:YES 完成:nil]; }); } -(void)view2:(NSNotification*) 通知{ NSLog(@"显示view2"); [自我dismissViewControllerAnimated:是完成:无]; [自我展示视图2]; } -(无效)showView2{ dispatch_async(dispatch_get_main_queue(), ^{ [self presentViewController:[[View1 alloc]init] 动画:YES 完成:nil]; }); } @结尾编辑:我忘了说 view1 最初显示时没有任何错误或问题。
编辑:view1 和 view2 的代码完全相同,只是它们发送不同的通知:
#import "View1.h" @界面 View1 () @结尾 @实现视图1 -(无效)加载视图{ [超级负载视图]; self.view.frame = [[UIApplication sharedApplication].keyWindow bounds]; // 在此处查看设置。 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [按钮添加目标:自己 动作:@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); [按钮 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]; } @结尾【问题讨论】:
-
如果在 View1 中按下按钮时出现错误,则需要显示该按钮的操作方法中的代码。
-
我已经添加了代码。两个视图是相同的,只是另一个发送通知以显示另一个视图
标签: ios objective-c viewcontroller presentviewcontroller