2016-05-16 112 views
-5

所以,我有导航控制器。有从根视图控制器继续其他视图控制器。访问导航堆栈中的当前视图控制器

当我想访问其他视图控制器时,我将覆盖prepareForSegue方法并使用destinationViewController属性。

但这对我来说并不好。我所有在prepareForSegue中的东西都会在每次调用segue时执行,但我不想要它。其次,它破坏了我的代码的逻辑:在performSegueWithIdentifier(实际上之前)执行跳转到代码中的其他地方。

如果我可以像访问Root ViewController一样访问其他视图控制器,例如通过关键字self,那将会很棒。

这是代码示例,使我的问题更加清晰的:

func startWorking() { 
    /*here we made some stuff for current VC 
... 
... 
*/ 

    //next we go to new View Controller 
    performSegueWithIdentifier("newVC", sender: nil) 

    //then all actions that I want to do begin at another method - prepareForSegue 
    //But I want get access to View Controller that user sees now! 
    //For example present some view: 

    let someView = UIView(frame: someFrame) 
    /*question subject*/.view.addSubview(somView) 
    } 

/问题受到/- 是我的赛格瑞和我的问题点提出的当前视图控制器。

+1

*“在prepareForSegue我的东西都将执行每当SEGUE被称为,但我不想要它“* - 那么不要把它放在那里......我很难理解你的问题究竟是什么,可以展示一些代码来证明你的问题是什么? – luk2302

+1

导航控制器有三种方法可以访问导航堆栈上的项目。你有没有试过其中的任何一个来看看它们是否适合你? – Desdenova

+0

是的!这是我的观点!我提出了Segue的新控制器,这是否意味着我必须在prepareForSegue方法中完成所有我想用新控制器做的事情? –

回答

3

谢尔盖Gamayunov,

可以使用总是访问在导航堆栈的顶部mostViewController,

let viewCOntroller = self.navigationController?.topViewController 

编辑

我相信,如果你不能让周围的prepareForSegue或自你的逻辑.navigationController?.topViewController你必须看看你的设计模式:)

话虽这么说,我理解你想要做的是访问performSegue后视图控制器不使用prepareForSegue,您可以使用此代码

func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) { 
     if viewController is YourDestinationViewControllerClass { 
      print("You have access to viewController loaded do whatever you want") 
     } 
} 

上述功能是导航控制器委托:)所以,你将不得不声明你的viewController来确认UINavigationControllerDelegate。像

class ViewController: UIViewController,UINavigationControllerDelegate 

override func viewDidLoad() { 
     super.viewDidLoad() 
     self.navigationController?.delegate = self 
} 

完蛋了,你是好去:)快乐编码好友:)

+0

我试图用'topViewController'属性: 'performSegueWithIdentifier( “NewVCSegue”,发件人:个体经营)? 让NEWVC = self.navigationController .topViewController' 但是'newVC'其实是VC我从哪里来? –

+0

@ sergey-gamayunov:我相信你非常困惑:)让我们帮助你:)准备segue是用来准备destinationViewController甚至在其呈现或加载到导航堆栈之前:)所以,如果你想配置viewCOntroller甚至在渲染之前,您应该使用segue.destinationViewController来为Segue做准备:)另一方面,假设您的视图控制器已经加载,并且是导航堆栈中的topViewController,您可以使用self.navigationController?.topViewController。这种方法会让你访问现有的实例 –

+0

谢谢你的回答! 但在此代码示例中,我没有使用'prepareForSegue',我使用'performSegueWithIdentifier'应该在导航堆栈顶部加载destinationVC ... –

相关问题