我有一台PhoneViewController : UIViewController
let phonePage = storyboard.instantiateViewControllerWithIdentifier("phoneViewController") as! PhoneViewController我从两个不同的控制器来展示它。
// UIViewController1
self.navigationController?.pushViewController(phonePage, animated: true)
// UIViewController2
self.presentViewController(phonePage.embedInNavController(), animated: true, completion: nil)我希望有一个必须检测哪个控制器是它的父控制器。我怎么能做到这一点呢?
发布于 2017-01-24 17:24:48
简短的答案是:
if let navController = self.navigationController {
return navController.viewControllers[navController.viewControllers.count - 1]
// take care if count <= 1
else {
return self.parent
}但这是你真正想要的吗?根据他的父母是谁,你试图实现什么行为?我不知道这个问题的答案,但是你应该让你的代码具有可读性。让我举一个例子来解释:
let phonePage = storyboard.instantiateViewControllerWithIdentifier("phoneViewController") as! PhoneViewController
// Option 1
self.navigationController?.pushViewController(phonePage, animated: true)
phonePage.mode = PhonePageMode.list
// Option 2
self.presentViewController(phonePage.embedInNavController(), animated: true, completion: nil)
phonePage.mode = PhonePageMode.grid
// In your PhoneViewController class
switch self.mode {
case .list: // present as a list
case .grid: // present as a grid
}的可读性比:
let phonePage = storyboard.instantiateViewControllerWithIdentifier("phoneViewController") as! PhoneViewController
// Option 1
self.navigationController?.pushViewController(phonePage, animated: true)
// Option 2
self.presentViewController(phonePage.embedInNavController(), animated: true, completion: nil)
// In your PhoneViewController class
guard let parent = self.parentViewController else { return }
if parent is ThisClassWhichWantsAList {
// present as list
} else if parent is ThisOtherClassWhichWantsAGrid {
// present as grid
}如果你想使用它的父元素作为一个条件来做不同的事情,你更愿意使用一个额外的属性。你未来的自我将会心存感激。
发布于 2017-01-24 17:29:09
你可以试试这段代码:
if let wd = self.window {
var vc = wd.rootViewController
if(vc is UINavigationController){
vc = (vc as UINavigationController).visibleViewController
}
if(vc is YourViewController){
//your code
}
}发布于 2017-01-30 20:08:02
如果你的视图控制器是从navigationViewController推送的,那么parentViewController中的父类是可用的,如果呈现了,那么presentationController中的父类是可用的。
您可以通过以下方式签到:
if let parentVC = self.navigationController.parentViewController{
//parentVC.className
}
if let presentedVC = self.navigationController?.presentationController{
//presentedVC.className
}https://stackoverflow.com/questions/41824102
复制相似问题