David Seek David Seek - 1 month ago 10
iOS Question

How to check if current UIViewController is part of UINavigationController

In my App the

UIViewController
"
ProfilVC
" is part of the
UINavigationController
"
nav
".

But in another Scene, i'm presenting "
ProfilVC
" to reuse the same
UIViewController
but with different data.

let vc = tweetsStb.instantiateViewController(withIdentifier: "ProfilVC") as! ProfilVC
self.present(vc, animated: true, completion: nil)


Within
didSelectRowAt
, I'm presenting another
UIViewController
. And here I need to check if
self
(
ProfilVC
) is currently part of the
nav
or presented on top.

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

let vc = tweetsStb.instantiateViewController(withIdentifier: "TweetCommentsVC") as! TweetCommentsVC
let post = tweets[(indexPath as NSIndexPath).section]
let cell = tableView.cellForRow(at: indexPath) as! TweetPostCell
vc.commentCounterString = cell.commentLabel.text!
vc.post = post
vc.avatare = avatare
nav?.present(vc, animated: true, completion: nil)
}


This code works perfect if
ProfilVC
is part of
nav
.

But I need
self.present(vc, animated: true, completion: nil)
if
ProfilVC
is presented on top.

What I need is something like this:

if(nav?.topViewController?.isKind(of: ProfilVC.self) != nil) {
nav?.present(vc, animated: true, completion: nil)
} else {
self.present(vc, animated: true, completion: nil)
}


The problem with this code is, that
ProfilVC
is always part of
nav
. I need to check if
ProfilVC
as
"self"
/"the current visible one" is part of
nav
or presented on top...

What is the best approach to accomplish my wanting? Help is very appreciated.

PS: Present the second instance of
ProfilVC
within
nav
is no option because I need
ProfilVC
in this case to overlapp the UINavigationBar of
nav
.

Answer

Every ViewController has a navigationController property. This property is nil if the ViewController is not part of a navigation stack.

Comments