xcode 如何在 UIView 中获取父导航控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5935186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get parent navigation controller in UIView
提问by omeraloni
I have created a UITabBarControllerin my app delegate.
where each tab bar item holds a different UINavigationControllerthat loads a custom UIViewControllerwith a NIB (using -pushViewController:).
Inside one of the navigation controller, I load a custom UIViewclass with a custom NIB also.
This view is loaded multiple times inside the UIViewController.
我UITabBarController在我的应用程序委托中创建了一个。其中每个选项卡栏项目都有一个不同的UINavigationController,它UIViewController使用 NIB加载自定义(使用-pushViewController:)。在其中一个导航控制器中,我还加载了一个UIView带有自定义 NIB的自定义类。该视图在UIViewController.
The custom UIViewhas a UIButton, that on the event of touching it, I want to push a new UIViewControlleron the stack.
Problem is that I 'lost' the UINavigationControllerthat holds the UIViewController.
I know I should use delegates, but haven't figured out who should which class should be the delegate.
自定义UIView有一个UIButton,在触摸它时,我想UIViewController在堆栈上推送一个新的。问题是我“丢失”了UINavigationController保存UIViewController. 我知道我应该使用委托,但还没有弄清楚谁应该是哪个类应该是委托。
Thanks in advance!
提前致谢!
回答by Cameron Hotchkies
Neither .navigationController or .tabBarController will be available for a UIView or UIViewController that's been created but not pushed onto a stack
.navigationController 或 .tabBarController 都不适用于已创建但未推送到堆栈上的 UIView 或 UIViewController
Either create a property on your View (or ViewController) class that is a UIViewController that is provided optionally after initialization or you could add a third argument to initWithNibName:bundle:
在您的 View(或 ViewController)类上创建一个属性,该属性是一个 UIViewController,在初始化后可选地提供,或者您可以向其中添加第三个参数 initWithNibName:bundle:
@interface CustomViewController : UIViewController
{
UIViewController *owner;
}
@property (nonatomic, assign) UIViewController* owner;
@end
Then in the owner ViewController:
然后在所有者 ViewController 中:
CustomViewController *cvc = [[CustomViewController alloc] initWithNibNamed:nil bundle:nil];
cvc.owner = self;
It's too bad .parentViewController is read-only, this would be the sensible place for this.
太糟糕了 .parentViewController 是只读的,这将是明智的地方。

