I have two UIViewController: A, B
Lets say there are two segues connecting them: C, D
Once a segue has been activated and I am in view B, can I know which segue got me here? C or D?
I don't know of any built-in mechanism for this, but you could have all your destination view controllers conform to a protocol SourceSegueProtocol that has a var to contain the invoking segue.
Then in the source view controller's prepare(for:sender:) method you could set that variable for destination view controllers that conform to the SourceSegueProtocol.
There is a prepare(for: segue) function that allows you to set a property in the new ViewController.
class OriginViewController : UIViewController {
...
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? SegueProtocol {
destination.transitionSegue = segue.identifier
}
}
}
class DestinationViewController : UIViewController, SegueProtocol {
var transitionSegue: String = ""
override func viewDidLoad() {
print("Segue: ", transitionSegue)
}
}
protocol SegueProtocol {
var transitionSegue : String { get set }
}
Edit: As per comment suggestion, it's better to expect a destination that conforms to a protocol rather than one of a specific type.
Related
I am working on a quiz app where in one view controller I am showing the questions and when I click on any of the questions it navigates to other view controller and shows question with options. Now, I want to use the same API which I have used in first view controller in second view controller. How can I do that?
In the first view controller I have used a struct like this:
struct Questions {
var id:String = ""
var user_id:String = ""
var questionset_id:String = ""
var name:String = ""
var type:String = ""
var timetosolve:String = ""
}
In the second view controller I have used the same struct in a variable like:
var data : [Questions] = []
But the problem is that I am not able to use the variables of the struct in the second view controller. I have tried to use the variable like:
questionLbl = data.name //here cannot find any variable named as 'name'
Here, questionLbl is the label where I want to use the variable.
You need to override func prepare(for segue: UIStoryboardSegue, sender: Any?) in first view controller and pass the data variable to the second one.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "YourSequeIdentifier" {
if let secondVC = segue.destination as? SecondVCClassName {
secondVC.data = self.data
}
}
}
Therefore you can access your data variable from second view controller. Please note that data variable is an array and you can't access values it like this data.name.
Your struct Questions should be declared in a global scope i.e in a new file "xyz.swift" or outside of ViewController class.
Which I am assuming as you said.
In the first view controller I have used a struct like this:
I have 4 views which contains a segue(it sends data from a json and store it in a variable called email) which i'm passing it like this:
A -> B(email) -> C(email)
... -> B(email) -> D(email)
So what i want to do is send back the information of the segue to:
C-> B
D-> B
Any idea how can i achieve this?
I think you're after an unwind segue.
To quote the docs:
...use the segue object to fetch the view controller being dismissed so that you can retrieve data from it.
Please see Creating an Unwind Segue on the View Controller Programming Guide for iOS.
The common way for passing data back is to use delegation. Delegation in Swift is done using protocols. So, for example, you declare the following protocol (please, use meaningful names for protocol and properties, the following is just an example):
protocol COrDDelegate {
func willReturn(someString: String)
}
Then, you add corresponding delegate properties to C and D view controllers:
class C: UIViewController {
weak var delegate: COrDDelegate?
...
}
(the same goes for D). You'll have to use weak modifier to avoid retain cycles. After that, call delegate's method right before dismissing the view controller:
func dismissMe() {
self.delegate?.willReturn(someString: "Meaningful data")
self.dismiss(animated: true, completion: nil)
}
In B, you implement the protocol:
extension B: COrDDelegate {
func willReturn(someString: String) {
print(someString)
}
}
and assign the delegate property to C or D in prepare(for:sender:) segue preparation method (just like you are probably doing for email):
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let c = segue.destination as? C {
c.email = self.email
c.delegate = self
}
}
Hopefully, I was able to convey the general idea. Good luck!
I have a view controller (containing my menu) presented on top of another view controller (my application).
I would need to access the presenting view controller (below my menu) from the presented view controller (my menu), for example to access some variables or make the presenting view controller perform one of its segues.
However, I just can't figure out how to do it.
I'm aware of the "presentingViewController" and "presentedViewController" variables but I didn't manage to use them successfully.
Any Idea ?
Code (from the presented VC, which as a reference to the AppDelegate in which the window is referenced) :
if let presentingViewController = self.appDelegate.window?.rootViewController?.presentingViewController {
presentingViewController.performSegue(withIdentifier: "nameOfMySegue", sender: self)
}
Here is a use of the delegation Design pattern to talk back to the presenting view controller.
First Declare a protocol, that list out all the variables and methods a delegate is expected to respond to.
protocol SomeProtocol {
var someVariable : String {get set}
func doSomething()
}
Next : Make your presenting view controller conform to the protocol.
Set your presenting VC as the delegate
class MainVC: UIViewController, SomeProtocol {
var someVariable: String = ""
func doSomething() {
// Implementation of do
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Your code goes here.
if let destVC = segue.destination as? SubVC{
destVC.delegate = self
}
}
}
Finally, when you are ready to call a method on the presenting VC (Delegate).
class SubVC: UIViewController {
var delegate : SomeProtocol?
func whenSomeEventHappens() {
// For eg : When a menu item is selected
// Set some Variable
delegate?.someVariable = "Some Value"
// Call a method on the deleate
delegate?.doSomething()
}
}
Assuming that VCApplication is presenting VCMenu, in VCMenu you can access VCApplication with:
weak let vcApplication = self.presentingViewController as? VCApplicationType
Your example self.appDelegate.window?.rootViewController?.presentingViewController is looking for the ViewController that presented the rootViewController - it will be nil.
EDIT
Per TheAppMentor I've added weak so there are no retain cycles.
I had an a problem with this code, this identifier didn't run with me
import UIKit
class RestaurantDetailViewController: UIViewController {
#IBOutlet var restaurantImageView: UIImageView!
var restaurantImage = ""
override func viewDidLoad () {
super.viewDidLoad ()
restaurantImageView.image = UIImage(named: restaurantImage)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showRestaurantDetail" {
if let indexPath = tableView.indexPathSelectedRow {
let destinationController = segue.destinationViewController as! RestaurantDetailViewController
destinationController.restaurantImage = restaurantImageView[indexPath.row]
}
}
}
}
The error is : Use of unresolved identifier 'tableView'
Looking for a solution.
Thanks,
The prepareForSegue method is obviously in the wrong class (copy and paste error?).
It belongs to the Master controller.
Do you have a tableview in your VIEWCONTROLLER ? If yes then create a IBOOutlet between your class and viewcontroller
you can see this question or this this for reference.
This behavior is called "scope" and is crucial to any programming language. Variables declared inside a method are neither visible outside it nor do they persist when that method has finished running. and in your case for creating tableView variable you have to create an IBOoutlet or you can define it programmatically too you can get more detail from here
and here
I am creating an application in which there are 6 view controller in storyboard. The thing is that data is shared between the default view controller and the first one ( say A and B) which i added. i am using the prepareforseque method for passing data. the problem started when i added two more view controller. lets say C and D i created two new swift files and changed the two view controller class name. i created a textbox and button in C and label in D. when i pressed the button, the value of the text field is not passing into the D view controller although i used the same methods and code which i used for A and B. do i have to do anything else when i want to pass data between two newly added view controller.
first viewcontroller in which when a button is pressed value 1 needed to be passed:
class PlaySelectMenu: UIViewController {
var value = Int()
#IBAction func twotofive(sender: AnyObject) {
value = 1
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let nextView : PlayGameView = segue.destinationViewController as! PlayGameView
nextView.x = value
}
}
the second view controller which receive the value and print it
import Foundation
import UIKit
class PlayGameView: UIViewController{
var x = Int()
override func viewDidLoad() {
super.viewDidLoad()
print(x)
}
}
here i have added both the view controller from the object library and not working with the default one which is present in storyboard by default. i dont know why these two viewcontroller are not working. please help.
Regards Dev
One solution would be to write the data out to NSUserDefaults and then read it back from NSUserDefaults in the other view controller. Probably not the proper or correct way to share data between two view controllers, but it's been a reliable work around for me.
Other than that, you'd need to share your code so that we can see what's occurring.
Can you post also the code in your controllers C & D. And also if you have copy/paste the code inside your first two controllers into the two others, are you sure that in your prepareForSegue method you have changed the name of the destination segue ?
Assuming you have created the segue in Storyboard:
All you need is to do is put all of needed updates in prepareForSegue because twotofive is called after prepareForSegue.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
value = 1
let nextView : PlayGameView = segue.destinationViewController as! PlayGameView
nextView.x = value
}
Since you have connected your segue from button click to view controller, when you press button segue is automatically called. Instead of connecting segue from button to VC, connect VC to VC. Then in button click method at the last add below line:
#IBAction func twotofive(sender: AnyObject) {
value = 1
self.performSegueWithIdentifier("<Name of the segue identifier>", sender: self)
}
This will call your prepareForSegue. If you are calling more then one VC using segue from a VC then you can use segue.identifier to check which VC was called as below
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "CVC" {
}