juelizabeth
juelizabeth

Reputation: 505

pass data from view controller to tabbarviewcontroller

I am segueing from a view controller to a tabbarcontroller and I want to pass data. I want to pass "sendAuthor" to the first view controller of the tabbarcontroller.

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "FirstVC" {

  let vc = (segue.destination as? UITabBarController)?.viewControllers?.first as? CommentProfileViewController

    vc?.sendAuthor = sendAuthor!
    vc?.Username.text = sendAuthor!

        print(sendAuthor!)
    }



    }

In order to make sure I am getting the right thing, I included a print statement print(sendAuthor!) and I am getting the correct print statement. I also included a print statement in the destination view controller but the print statement returns nil

var sendAuthor: String?

override func viewDidLoad() {
        super.viewDidLoad()
print(self.sendAuthor)

}

Upvotes: 0

Views: 44

Answers (1)

vacawama
vacawama

Reputation: 154583

Your VC is imbedded in a UINavigationController. You need to take that into account as well:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "FirstVC" {
       guard let tabbar = segue.destination as? UITabBarController,
             let navcon = tabbar.viewControllers?.first as? UINavigationController,
             let vc = navcon.topViewController as? CommentProfileViewController
             else { return }

       vc.sendAuthor = sendAuthor!
       vc.Username.text = sendAuthor!

       print(sendAuthor!)
    }
}

Upvotes: 1

Related Questions