Access the Instance of a Viewcontroller from Another in Swift

Access the instance of a Viewcontroller from another in swift

1. If the view controller containing the textfield can call (with a segue) the view controller containing the label...

Add a new Cocoa Touch class file in your project, name it FirstViewController and set the following code in it:

import UIKit

class FirstViewController: UIViewController {

@IBOutlet weak var textField: UITextField! // FIXME: link this to the UITextField in the Storyboard!!!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let controller = segue.destinationViewController as! SecondViewController
controller.text = textField.text
}

}

Add a new Cocoa Touch class file in your project, name it SecondViewController and set the following code in it:

import UIKit

class SecondViewController: UIViewController {

var text: String?
@IBOutlet weak var label: UILabel! // FIXME: link this to the UILabel in the Storyboard!!!

override func viewDidLoad() {
super.viewDidLoad()

label.text = text
}

}

In the Storyboard, embed the first view controller in a UINavigationController. Link the first view controller to the second with a UIButton or a UIBarButtonItem. Set the name of the first view controller to FirstViewController and the name of the second view controller to SecondViewController. Create a UITextField in the first view controller. Create a UILabel in the second view controller. Link the textfield and the label to their respective declarations in FirstViewController and SecondViewController.



2. If the view controller containing the label can call (with a segue) the view controller containing the textfield...

Here, this is a perfect protocol/delegate case. You may find a lot of stuff on StackOverflow dealing with this. However, here is a rough example.

Add a new Cocoa Touch class file in your project, name it FirstViewController and set the following code in it:

import UIKit

class FirstViewController: UIViewController, DetailsDelegate {

@IBOutlet weak var label: UILabel! // FIXME: link this to the UILabel in the Storyboard

func updateLabel(withString string: String?) {
label.text = string
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let controller = segue.destinationViewController as! SecondViewController
controller.delegate = self
}

}

Add a new Cocoa/Cocoa Touch class file in your project, name it SecondViewController and set the following code in it:

import UIKit

protocol DetailsDelegate: class {
func updateLabel(withString string: String?)
}

class SecondViewController: UIViewController {

weak var delegate: DetailsDelegate?
@IBOutlet weak var textField: UITextField! // FIXME: link this to the UITextField in the Storyboard

override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)

delegate?.updateLabel(withString: textField.text)
}

}

In the Storyboard, embed the first view controller in a UINavigationController. Link the first view controller to the second with a UIButton or a UIBarButtonItem. Set the name of the first view controller to FirstViewController and the name of the second view controller to SecondViewController. Create a UILabel in the first view controller. Create a UITextField in the second view controller. Link the textfield and the label to their respective declarations in FirstViewController and SecondViewController.

Access current instance of view controller from app delegate in swift?

You have two options, the second one is better by design.

First option: (what you want)

I don't know the structure of your view controllers, so let me assume you have a root view controller, you could get it from AppDelegate via:

rootVC = self.window?.rootViewController

And if you want to get the presented view controller from the root view controller (like many apps, the presented view controller is a tab bar controller):

guard let tabBarController = rootVC.presentedViewController as? TabBarController else {
return
}

Once you get your tab bar controller, you can find the view controller in the array of view controllers:

tabBarController.viewControllers

Essentially, what I'm trying to say is you have to jump through your view controllers starting from the root to get to the controller you want, then grab the variable from there. This is very error prone, and generally not recommended.

Second option (better practice):

Have your view controller register as an observer for the UIApplicationWillResignActiveNotification notification. This will allow you to do whatever you want from the view controller when your app is about to enter background.

Accessing view controller methods inside another class [Swift]

I am not sure why getting this error because my DataSource class is inside my ViewController class.

That makes no difference. Declaring one class inside of another merely namespaces the inner class, i.e. it is now called AnimalsVC.DataSource. It does not cause one instance of the inner class to be able to see magically inside an instance the outer class (and indeed it is completely unclear what instances we would be talking about).
Your nesting of class declarations is useless, so you might as well not do it.

Instead, if DataSource needs to see inside AnimalsVC, do what you would normally do: give your DataSource instance a reference to the AnimalsVC instance:

class AnimalsVC: UIViewController {
var animalsArray = // ...
}

class DataSource: UITableViewDiffableDataSource<Int, Animal> {
weak var vc : AnimalsVC?
// ...
}

When you create your DataSource instance, set its vc to self. Now the DataSource can consult the instance properties of the AnimalsVC instance.

(Actually, what I do in my own code is give my UITableViewDiffableDataSource subclass a custom designated initializer. That way, I can create the data source and hand it a reference to the view controller all in one move.)

Swift 5.1 Can I access a struct instance declaration in another view controller?

This can be done in a multitude of ways. First I would say if you are passing it to a detail view controller then use preparForSegue method.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "someSegue" {
let vc = segue.destination as! YourDetailVC
vc.user = self.user
}
}

For other ways of passing data, you should research call backs, delegation, and Notification Center.

Also structs automatically come with a memberwise initializer. So you can initialize it as follows:

let user = User(name: "John")

How do I access an outlet from another View Controller? (Swift)

Short answer: Don't do that. You should treat a view controller's views as private.

If you mess with another view controller's views you are violating the principle of encapsulation. One module should not depend on the implementation details of another module.

Instead, add a Bool function showTrophy(_ show: Bool).

Keep a pointer to the other view controller (don't create a new instance, as aheze points out.)

In your AccomplishmentsViewController's showTrophy method set the visibility of your trophy icon appropriately.

Accessing UITableViewController from another ViewController

you should set UITableViewController instance as a variable of a new view controller.

e.g.,

class VC1: UIViewController {
func launch() {
let vc2 = VC2()
vc2.previousVC = self
present(vc2,..)
}
}

claass VC2: UIViewController {
weak var previousVC: VC1?
}

you can do the same setup if you use segues:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SomeSegue" {
if let vc2 = segue.destination as? VC2 {
vc2.previousVC = self
}
}
}

Programmatically get instance of view controller

UITabBarControllers are most often used as applications' rootViewController. While you are not using storyboards, after app launch, if you are setting an instance of TabsController as your app's window's rootViewController, you can refer to this instance from anywhere in your app like so:

if let tabsController = UIApplication.sharedApplication().delegate?.window??.rootViewController as? TabsController {
tabsController.selectedIndex = 2
}

Accessing variables from another ViewController in Swift

Everything by default in swift is public, and thus if you declare something like this:

class SomeViewController: UIViewController {
var someVariable: SomeType = someValue

init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
}

You can access it as long as you have an instance of it:

var myCustomViewController: SomeViewController = SomeViewController(nibName: nil, bundle: nil)
var getThatValue = myCustomViewController.someVariable


Related Topics



Leave a reply



Submit