I have a Login project. The first view controller is NavController and I need to pass user data to tabBarController where I have 3 NavigationControllers.
I tried this.
let openNewVC = self.storyboard?.instantiateViewControllerWithIdentifier("mainNavID") as! UITabBarController
//openNewVC.token = token!
self.navigationController?.pushViewController(openNewVC, animated: true)
You can pass the data from your first view Controller to view controllers which are embedded like as below in UITabbarController.
UITabBarController -> UINavigationController -> UIViewController
You need to traverse the viewControllers instance of UITabBarController and UINavigationController in order to get the instance of UIViewController. Once you will get the instance of 'UIViewController' which is embedded into UITabbarController, you can assign the data as required.
For Example
if let tabBarController = self.storyboard?.instantiateViewControllerWithIdentifier("mainNavID") as? UITabBarController {
// Now you need to get View Controllers array from tabBarControllers which is UINavigationControllers
if let navigationControllers = tabBarController.viewControllers as? [UINavigationController] {
for navigationController in navigationControllers {
//Now you need to get the viewControllers from navigationController stack,
let viewControllers = navigationController.viewControllers
//Now you can assing desired value in viewControllers, I am assuming you need to assign the same value in all viewControler
for viewController in viewControllers {
}
}
}
}
The best way to pass the data in this kind of architecture using Singleton, Assume you created a class Session which member variable token.
class Session {
//Singleton
static let sharedInstance = Session()
//Token which you assign and you can use through out application
var token : String? = nil
}
Now, you can assign the token while pushing the UITabbarController.
let openNewVC = self.storyboard?.instantiateViewControllerWithIdentifier("mainNavID") as! UITabBarController
Session.sharedInstance.token = token
//openNewVC.token = token!
self.navigationController?.pushViewController(openNewVC, animated: true)
Same token you can use within UIViewController
override func viewDidLoad() {
super.viewDidLoad()
if let token = Session.sharedInstance.token {
//Now you have assigned token
}
}
You could try to set the values to the openNewVC as you would set a normal property.
Example:
//set instance
var openNewVC = self.storyboard?.instantiateViewControllerWithIdentifier("mainNavID") as! UITabBarController
// set properties
openNewVC.myFancyString = "Hello world!"
// set view controller active
self.navigationController?.pushViewController(openNewVC, animated: true)
Related
I'm learning Programmatic UI and am a little bit obsessed with clean code.
I'm currently building a TabBarVC so that I can manage all of my VC's but I get an error message while doing this.
import UIKit
class MainTabBarVC: UITabBarController {
let firstVC = FirstVC()
let secondVC = SecondVC()
let firstNavVC = UINavigationController(rootViewController: firstVC) // Cannot use instance member 'firstVC' within property initializer; property initializers run before 'self' is available
let secondNavVC = UINavigationController(rootViewController: secondVC) // Cannot use instance member 'secondVC' within property initializer; property initializers run before 'self' is available
let viewControllers = [firstNavVC, secondNavVC]
override func viewDidLoad() {
super.viewDidLoad()
self.setupViews()
}
func setupViews() {
// Nav Configs
self.firstVC.view.backgroundColor = .systemBackground
self.firstVC.navigationItem.title = "First Nav"
self.secondVC.view.backgroundColor = .systemBackground
self.secondVC.navigationItem.title = "Second Nav"
// Tab Configs
self.firstNavVC.tabBarItem.title = "First TAB"
self.secondNavVC.tabBarItem.title = "Second TAB"
}
}
I know if I put firtNavVC, secondNavVC, and viewcontrollers inside the setupViews it is gonna work but I don't like it when one function has too many lines of codes especially when it gets bigger.
So except for my question, are there any extension or enum functions that I can easily manage all of my UINavigationController, UITabBarController, and UIViewController such as enumeration that can call the function whenever I need to call or add a new VC.
You could change your lets into lazy vars.
class MainTabBarVC: UITabBarController {
lazy var firstVC = FirstVC()
lazy var secondVC = SecondVC()
lazy var firstNavVC = UINavigationController(rootViewController: firstVC)
lazy var secondNavVC = UINavigationController(rootViewController: secondVC)
lazy var viewControllers = [firstNavVC, secondNavVC]
override func viewDidLoad() {
super.viewDidLoad()
self.setupViews()
}
However, I think your impulse to maintain instance property references to all these view controllers is mistaken. What I would do is just move the lets into setupViews. You don't need a permanent reference to any of these objects; you just need to create them, configure them, and assign the view controllers as children of your tab bar controller (your code is missing that crucial step, by the way).
I am new to Swift and Xcode. I am building an Financial Expense ios app.
In my first view controller, I created a referencing outlet for a label called expenseNum.
In my second view controller, I have a function for a button called Add Expense. When it is clicked, I need it to update the expenseNum variable with the amount of the expense.
What is the best way to go about this? I had created an object of the first view controller class and accessed it like "firstviewcontroller.expenseNum" but this will create a new instance of the class and I need it to be all the same instance so it can continuously add to the same variable. Thanks for the help!
You need a delegate
protocol SendManager {
func send(str:String)
}
In first
class FirstVc:UIViewcontroller , SendManager {
func send(str:string) {
self.expenseNum.text = str
}
}
when you present SecondVc
let sec = SecondVc()
sec.delegate = self
// present
In second
class SecondVc:UIViewcontroller {
var delegate:SendManager?
#IBAction func btnClicked(_ sender:UIButton) {
delegate?.send(str:"value")
}
}
// setting delegate
in viewDidLoad of SecondVc
if let first = self.tabBarController.viewControllers[0] as? FirstVc {
self.delegate = first
}
There are several ways you can pass data from ViewController2 to another ViewController1
The best way here is Protocol Delegates
Please follow below steps to pass data
In Your SecondViewController from where you want to send data back declare a protocol at the top of class declaration
protocol SendDataBack: class {
func sendDataFromSecondVCtoFirstVC(myValue: String)
}
Now in the class , declare a object of your protocol in same ViewController
weak var myDelegateObj: SendDataBack?
And now in your Add Expense button action just call the delegate method
myDelegateObj?.sendDataFromSecondVCtoFirstVC(myValue: yourValue)
Now go to your first ViewController
the place from where you have pushed/present to SecondViewController you must have taken the object of SecondVC to push to push from first
if let secondVC = (UIStoryboard.init(name: "Main", bundle: nil)).instantiateViewController(withIdentifier: "secondVCID") as? SecondViewController {
vc?.myDelegateObj = self
self.navigationController?.pushViewController(secondVC, animated: true)
**OR**
self.present(secondVC, animated: true, completion: nil)
}
now in your FirstViewController make an extension of FirstViewVC
extension FirstViewController: SendDataBack {
func sendDataFromSecondVCtoFirstVC(myValue: String) {
}
}
I think you can make a variable in your properties in second ViewController (before viewDidLoad method)
var delegate: FirstViewController? = nil
and use from the properties of the first view controller anywhere of the second view controller.
delegate!.mainTableView.alpha=1.0
//for example access to a tableView in first view controller
The simplest way to achieve this is to use a public var. Add a new Swift file to your project, call it Globals. Declare the public variable in Globals.swift like so:
public var theValue: Int = 0
Set its required value in the first ViewController, and you'll find you can read it in the second with ease.
I have two UIViewControllers, vc1, and vc2. vc1 is embedded in a UIViewController which is embedded in a UITabBarController, but vc2 is not embedded in either.
How do I pass information from vc2 to vc1? After a user performs an action the data is saved and vc2 simply closes, so there isn't a segue to pass information. Obviously I can't reference vc1 through the Navigation stack or the TabController.
I could save to the AppDelegate, but I've read this isn't a good practice.
This is the code I use to pass information from AppDelegate to vc1 I tried it in vc2, but obviously it failed.:
let tabBarController = window!.rootViewController as! UITabBarController
if let tabBarViewControllers = tabBarController.viewControllers {
let navPostViewController = tabBarViewControllers[0] as! UINavigationController
let user = User(context: managedObjectContext)
if user.userID != nil {
print("User is loggedIn")
isUserLoggedIn = true
} else {
print("User is not loggedIn")
isUserLoggedIn = false
}
let postViewController = navPostViewController.topViewController as! PostViewController
postViewController.managedObjectContext = managedObjectContext
}
First off, I've never got into the habit of using segue to pass information. What i would recommend is that you implement the delegate pattern whenever you need to pass data between two objects. Its a lot cleaner.
For instance lets say you wanted to pass data between LoginViewController and PostViewController:
protocol LoginViewControllerDelegate:NSObjectProtocol{
func userDidLogin(data:String)
}
class LoginViewController:UIViewController {
weak var delegate:LoginViewControllerDelegate?
...
#IBAction func loginButtonPressed(sender:UIButton) {
//Perform login logic here
//If successful, tell the other controller or the 'delegate'
self.delegate?.userDidLogin(data:"Some data....")
}
}
class PostViewController:UIViewController, LoginViewControllerDelegate {
func userDidLogin(data:String) {
print("Got data from login controller: \(data)")
}
}
//How you might use this
loginViewController.delegate = postViewController
One caveat to remember is to never try to have strong references between two objects i.e. do not have the objects hold onto each other or this will cause a memory leak.
I have a UICollectionViewCell class "ProductCell"; I am trying to access the current navigation controller in order to update a barbuttonicon. I have tried the following code as this is what I use in my other UIViewControllers:
let nav = self.navigationController as! MFNavigationController
nav.updateCartBadgeValue()
However it states that the
value of type ProductCell has no member navigationController
I am aware that this is not a UIViewController but surely you should be able to access the current navigation controller the same way?
I also know that you can access the navigation controller by using UIApplication in the following way:
let navigationController = application.windows[0].rootViewController as! UINavigationController
I am not sure if that is a good way of doing it though.
Any help is much appreciated
Thanks
UIResponder chain will help here.
You can search the responder chain to find the controller for any view
extension UIView {
func controller() -> UIViewController? {
if let nextViewControllerResponder = next as? UIViewController {
return nextViewControllerResponder
}
else if let nextViewResponder = next as? UIView {
return nextViewResponder.controller()
}
else {
return nil
}
}
func navigationController() -> UINavigationController? {
if let controller = controller() {
return controller.navigationController
}
else {
return nil
}
}
}
controller() will return the closest responder that is of type UIViewController
Then on the returned controller you just need to find its navigation controller. You can use navigationController() here.
The simplest way is to add a property to you cell class that weakly references a UINavigationController
weak var navigationController: UINavigationController?
you will need to assign it in your cellForRow(atIndexPath:_) method.
let cell = tableView.dequeueReusableCell(withIdentifier: "yourReuseID") as! YourCellClass
cell.navigationController = navigationController //will assign your viewController's navigation controller to the cell
return cell
Unless things change, this is a good way to do it. To give you an example of a messier solution... You could add a
let hostViewController:UIViewController
property to your cell and add an initializer to handle it
let cell = ProductCell(vc: self)
But I don't think that's a better way to do it. your suggestion works fine.
let navigationController = application.windows[0].rootViewController as! UINavigationController
What is the best way to pass a UInavigationController and also pass variables to a new viewController. I know how to do one or the other but not both at the same time. Thank you in advance
this is my current code
func(){
let vc = storyboard?.instantiateViewControllerWithIdentifier("messagesViewController") as! UINavigationController
let posts = self.postList[indexPath.row]
//this is the var that i want to past
//vc.previousViewMessageId = posts.postKey
self.presentViewController(vc, animated: true, completion: nil)
}
If I understand you correctly, you have a view controller that can present a second VC. And this VC is embedded in a UINavigationController. What you don't know how to do, is to pass data from the first VC, to the navigation controller, then to the second VC.
Here is a brute force solution. It's not beautiful, but it works anyway.
Make your own UINavigationController subclass:
class DataPasserController: UINavigationController {
var previousViewMessageId: SomeType?
override func viewDidLoad() {
if let vc = self.topViewController as? YourSecondViewController {
vc.previousViewMessageId = self.previousViewMessageId
}
}
}
Now you can add a navigation controller in the storyboard, set its class to DataPasserController, and connect the second VC to it as its root view controller.
Now suppose you have got an instance of DataPasserController by calling instantiateViewControllerWithIdentifier, you can do this:
yourDataPasserControllerInstance.previousViewMessageId = posts.postKey
And present the instance!
To pass a value to your Navigation Controller's Root View Controller, you access viewControllers[0] and cast it to the class of your Messages View Controller (the controller that has the previousViewMessageId property):
func () {
let messagesNC = storyboard?.instantiateViewControllerWithIdentifier("messagesViewController") as! UINavigationController
let messagesVC = messagesNC.viewControllers.first as! MessagesViewController
messagesVC.previousViewMessageId = postList[indexPath.row].postKey
presentViewController(messagesNC, animated: true, completion: nil)
}
What you have there is simply presenting a view controller... You are skipping the navigation controller.
What you need to do is present the new view controller inside the navigation controller. Once you have done that, it will show correctly. You can also pass the variables after you've created the vc variable.
This presents the new viewController (vc) within the navigation controller...
self.navigationController?.pushViewController(vc, animated: false)
This sets the variable in the new viewController (vc) (you are correct)
vc.previousViewMessageId = posts.postKey
So complete:
func(){
let vc = storyboard?.instantiateViewControllerWithIdentifier("messagesViewController") as! MessagesViewController
let posts = self.postList[indexPath.row]
//this is the var that i want to past
vc.previousViewMessageId = posts.postKey
navigationController?.pushViewController(vc, animated: false)
}
PS. While not part of the question, I feel I should still mention... Use of the word self should be left to necessity only. In other words, don't use it when it isn't needed. for example self.postList[indexPath.row] :)
https://github.com/raywenderlich/swift-style-guide#use-of-self