我在一个UIView子类中创建了一个按钮。我需要通过这个按钮调用popViewControllerAnimated,但都不起作用!而且我也看不到rootViewController的viewController推送。下面是我的代码:
- (void)SomeFunction {
backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton showsTouchWhenHighlighted];
[backButton addTarget:self
action:@selector(backToMainMenu)
forControlEvents:UIControlEventTouchUpInside];
}
- (void)backToMainMenu {
[self.window.rootViewController.navigationController popViewControllerAnimated:YES];
NSLog(@"back");
}我将代码更改为:
UINavigationController *vc = self.window.rootViewController.navigationController;
[vc.navigationController popViewControllerAnimated:YES];但是什么也没发生。
发布于 2015-03-16 20:12:38
我认为您需要使用适当的目标格式,该格式将按钮作为参数。所以像这样添加目标函数:
[backButton addTarget:self
action:@selector(backToMainMenu:)
forControlEvents:UIControlEventTouchUpInside];目标应该是这样的:
- (void) backToMainMenu:(UIButton *) sender{
[self.navigationController popViewControllerAnimated:YES];
}发布于 2015-03-16 20:20:13
更好的选择是使用委托模式,因为在您当前的逻辑中,您正在破坏MVC架构和指导方针。
在子视图类中创建一个Protocol。这个委托的接收者是视图控制器类,您可以从中显示视图。在按钮的事件处理中,调用委托方法,然后从视图控制器中成功调用popViewControllerAnimated。
发布于 2015-03-16 20:24:30
我相信你的基本问题(除了设计)在(无效)backToMainMenu中...self.window.rootViewController.navigationController将为空,因此此方法不执行任何操作
来自UIViewController类引用:如果接收器或其祖先之一是导航控制器的子级,则此属性包含拥有的导航控制器。如果视图控制器没有嵌入到导航控制器中,则此属性为nil。
所以你看,rootViewController不能嵌入到导航控制器里面,它是最底层的。
你为什么不测试一下:
{
UINavigationController *vc = self.window.rootViewController.navigationController;
if (vc==nil){
NSLog(@"nav controller is nil, this will never work");
}
[vc.navigationController popViewControllerAnimated:YES];
}我也完全同意@rory关于设计的回答。
PS为了推送这个viewController,你真的创建了一个UINavigationController吗?
https://stackoverflow.com/questions/29076259
复制相似问题