I'm just looking for a way to detect which Segue Identifier activated the current viewController. I'm in need of doing this as I have conditions that might not be met, but can be referenced from another viewController, which then I'd like to highlight a few labels using that specific segue ID. Has anyone needed to do this before? How did you approach this?
Probably you should create on your "current view controller" a property to store the name of the segue and then on the controller which uses the segue to instantiate your "current view controller" you assign it before fire the segue execution:
ObjectiveC:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([[segue identifier] isEqualToString:#"YourSegueName"]) {
// Get destination view
CurrentVC *vc = [segue destinationViewController];
// Get button tag number (or do whatever you need to do here, based on your object
vc.segueName = #"YourSegueNam";
}}
Swift 3:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "YourSegueName"
{
if let destinationVC = segue.destination {
destinationVC.segueName = segue.identifier
}
}
}
Is that what you need? Let me know.
Anyway I still do not know why you want to do that.
This is not possible. You cannot simply get the "current Segue" at any point in the app. Because Segues Exist only at specific points in time during your Apps Life cycle. That being when your app is preparing for the transition from one view controller to another and also during the actual visual transition.
For more info follow https://developer.apple.com/documentation/uikit/uistoryboardsegue
Related
I'm trying to pass an annotation's title to the second view controller with the calloutAccessoryControlTapped method like this:
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view
calloutAccessoryControlTapped:(UIControl *)control
{
//My second VC's UILabel outlet
self.lblAnnotationTitle.text = view.annotation.title;
[self performSegueWithIdentifier:#"gymDetails" sender:self];
}
When the view controller shows up, the label is not updated yet. Why is that so?
Also, is this the right way to pass properties to another view controller? If not, what is a better way to do this?
You should implement prepareForSegue and pass the value there
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"gymDetails"]) {
GymDetailViewController *destViewController = segue.destinationViewController;
destViewController.ivar = #"Your Text here";
}
}
Then in your view did load you should do like
lblAnnotationTitle.text = ivar;
The better way to do that is to do inside the -prepareForSegue method.
Inside that method by looking at the identifier you can grab the destinationViewController and update with you model.
Pay attention those aspects:
if your view controller is contained inside a container view controller the destination view controller is the container view controller, so you need to extract your view controller from it
Until the segue is finished your view controller view is not loaded, this means that the connections between the outlet are still at nil, so if you force the label to be updated with the text, nothing will happen. One way to do is pass the text as a "model" and update the label inside the -viewDidLoad method of the destination view controller.
Try this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "xxx" {
if let destination = segue.destination as? XXX {
destination.xx = xx
}
}
}
I have IOS Swift program, using Storyboards with NavigationController.
There are two Views, lets call them mainView, secondView.
From the mainView I have BarButtonItem to go to secondView. When pressing that button, it triggers prepareForSegue function in the mainView with segue.identifier = "secondView"
When I have opend e.g. the secondView, I have two BarButtonItems for Cancel and Save. When pressing either of them the prepareForSegue function in that view is triggered, but now the segue.identifier = nil.
I would have expected to have the segue.identifier = "cancel" or "save" depended on the button pressed in that view.
Am I misunderstanding the segue functionality? Can anyone try to enlight me about this, as this looks like a very important and useful part of storyboards and navigation - but somehow I am not getting it right.
Have you created actions for the cancel and save buttons on your second view?
Right click and drag from your storyboard to the view controller code and select action from the dropdown.
Then in the action method, perform your segue.
#Garret, #rdelmar, #syed-tariq - thank you for pointing me into the right direction.
It turned out that Unwind Segue got me on track: Xcode Swift Go back to previous viewController (TableViewController)
But I also found one error I was doing in my storyboard, as I had Navigation Controller on all views (yes, I know - stupid when you know better): How do I segue values when my ViewController is embedded in an UINavigationController?
The final puzzle was to learn about the Protocols and Deligates to get this all to work.
Putting this together, then in short:
I created a protocol in my second view (above the class)
protocol MyDelegate: class {
func getMyList(sender: MySecondView) -> [NSManagedObject] //returns a CoreData list
}
Then I created a delegate variable in my second view
weak var datasource: MyDelegate!
In my first view I implemented the protocol, which was just one simple function returning a list that I needed in my second view
In my first view I have prepareForSegue where I catch the correct segue.identifier and there I set the delegate by going through segue.destinationViewController, like this
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if segue.identifier == "mySegue" {
let vc = segue.destinationViewController as! MySecondView
vc.delegate = self
}
}
and that was about it - now magically the flow is correct, segues happening, deligates passing correctly, and all good :)
I've just figured out what is an unwind segue and how to use it with the great answers from this question. Thanks a lot.
However, here's a question like this:
Let's say there is a button in scene B which unwind segues to scene A, and before it segues I want something to be done, such as saving the data to database. I created an action for this button in B.swift, but it seems it goes directly to scene A without taking the action appointed.
Anyone knows why or how to do this?
Thank you.
You can do it the way you describe, or by using a prepareForSegue override function in the viewController you are unwinding from:
#IBAction func actionForUnwindButton(sender: AnyObject) {
println("actionForUnwindButton");
}
or...
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
println("prepareForSegue");
}
The first example is as you describe. The button is wired up to the unwind segue and to the button action in Interface Builder. The button action will be triggered before the segue action. Perhaps you didn't connect the action to the button in interface builder?
The second example gives you have access to the segue's sourceViewController and destinationViewController in case that is also useful (you also get these in the unwind segue's function in the destination view controller).
If you want to delay the unwind segue until the button's local action is complete, you can invoke the segue directly from the button action (instead of hooking it up in the storyboard) using self.performSegueWithIdentifier (or follow wrUS61's suggestion)
EDIT
you seem to have some doubts whether you can work this by wiring up your button both to an unwind segue and to a button action. I have set up a little test project like this:
class BlueViewController: UIViewController {
#IBAction func actionForUnwindButton(sender: AnyObject) {
println("actionForUnwindButton");
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
println("prepareForSegue");
}
}
class RedViewController: UIViewController {
#IBAction func unwindToRed(sender: UIStoryboardSegue) {
println("unwindToRed");
}
}
BlueViewController has a button that is connected in the storyboard to BOTH the unwindToRed unwind segue AND the actionForUnwindButton button. It also overrides prepareForSegue so we can log the order of play.
Output:
actionForUnwindButton
prepareForSegue
unwindToRed
Storyboard:
EDIT 2
your demo project shows this not working. The difference is that you are using a barButtonItem to trigger the action, whereas I am using a regular button. A barButtonItem fails, whereas a regular button succeeds. I suspect that this is due to differences in the order of message passing (what follows is conjecture, but fits with the observed behaviour):
(A) UIButton in View Controller
ViewController's button receives touchupInside
- (1) sends action to it's method
- (2) sends segue unwind action to storyboard segue
all messages received, and methods executed in this order:
actionForUnwindButton
prepareForSegue
unwindToRed
(B) UIBarButtonItem in Navigation Controller Toolbar
Tool bar buttonItem receives touchupInside
- (1) sends segue unwind action to storyboard segue
- (2) (possibly, then) sends action to viewController's method
Order of execution is
prepareForSegue
unwindToRed
actionForUnwindButton
prepareForSegue and unwind messages received. However actionForUnwindButton message is sent to nil as viewController is destroyed during the segue. So it doesn't get executed, and the log prints
prepareForSegue
unwindToRed
In the case of (B), the viewController is destroyed before the method reaches it, so does not get triggered
So it seems your options are...
(a) use a UIButton with action and unwind segue
(b) trigger your actions using prepareForSegue, which will be triggered while the viewController is still alive, and before the segue takes place.
(c) don't use an unwind segue, just use a button action. In the action method you can 'unwind' by calling popToViewController on your navigation controller.
By the way, if you implement a toolBar on the viewController (not using the navigation controller's toolbar) the result is the same: segue gets triggered first, so button action fails.
If you are able to perform unWind Segue Successfully. Then the method in destination View Controller is called just before the segue take place, you can do what ever you want in source viewcontroller by using the segue object.
- (IBAction)unwindToThisViewController:(UIStoryboardSegue *)unwindSegue
{
CustomViewController *vc = (CustomViewController*) unwindSegue.sourceViewController;
[vc performAnyMethod];
[vc saveData];
NSString *temp = vc.anyProperty;
}
if you want your logic in source Controller then implement prepareForSegue in Scene B and set the unWind segue Identifier from Storyboard > Left View hierarchy Panel > under Exit in Scene B.
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([[segue identifier] isEqualToString:#"backToSource"])
{
NSLog(#"Going Back");
}
}
At first, you should call the send data function in prepareForSegue method.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([[segue identifier] isEqualToString:#"UnwindIdentifier"]) {
// send data
}
}
If you don't want to let unwind segue happen before getting response from the server, you should override
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
method and return NO;. Then you can perform segue manually when you get the server response by calling:
[self performSegueWithIdentifier:#"UnwindIdentifier" sender:sender];
I have two controllers named RootViewController and CountrySelectionActivityViewController. I have written a prepareForSegue function to pass data from first to the second view. I have a navigation controller in which the view is embedded in. So, here is my code:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "next") {
let mynavigationController = segue.destinationViewController as UINavigationController
let vc = mynavigationController.topViewController as CountrySelectionActivityViewController
vc.countries = countries
}
}
If I comment out this code, my app runs and moves to the next viewcontroller. Though, the data is not passed if this function is not implemented. What is wrong with my implementation?
I wanted to achieve the same objetive as you, passing variables between controllers when performing a segue.
My solution was to create two variables in each controller and related them through a custom segue.
In order to define the custom segue a new class is creaded: CustomPushSegue.m. This file has the implementation of -(void)perfom. This class is of type UIStoryboardSegue and has origin and destination variables of type UIViewController.
Then the idea is to cast each viewController of destination and origin as the custom controllers and pass the variables:
#import "OriginController.h"
#import "DestinationController.h"
-(void) perform {
UIViewController *destinationController = self.setinationViewController;
UIViewController *originController = self.sourceViewController;
if ([[self identifier] isEqualToString : #"Segue"]){
(DestinationController*) destinationController.var1 = (OriginController*) originController.var1;
}
//Stuff related to the performance of the Segue goes here
}
If you require further information, please ask. I can send you some sample files.
Based on the Stanford iOS course I am playing with modal view controllers. In the demo they have a button that would launch a modal view and when it is clicked the function prepareForSegue is called. I mimicked the code and implementation into my project with the only difference is that my demo is on an iPhone storyboard and theirs is on the iPad.
I noticed that while my modal view controller is coming up, it does not call prepareForSegue prior to that. I searched the Stanford project to see where they may register any segue behavior before prepareForSegue is called but there is no evidence. Can anyone shed some light on this. I searched stack overflow and all I found were that users were missing the call implementation of performSegueWithIdentifier. However, in the Stanford demo they never do that.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier hasPrefix:#"Create Label"]) {
AskerViewController *asker = (AskerViewController *)segue.destinationViewController;
asker.question = #"What do you want your label to say?";
asker.answer = #"Label Text";
asker.delegate = self;
}
}
Here is an example of there storyboard:
Here is an example of my storyboard:
In the debugger when I stop in the Stanford Demo code the call stack shows that the storyboard is performing a segue action, what do I need to configure in my storyboard to achieve the same result?
Well, as it turns out, my view controller where button calls the modal view did not have the right class where prepareForSegue is implemented. It was the default UIViewController instead of my custom class.
The way I figured it out was by putting a break point in viewDidLoad and even that was not breaking and thus I suspected that in the storyboard I did not have the right class associated with the view where the button is implemented.
For others with this problem, if you are now using Swift 3 having the following function will not throw errors as it is the correct syntax but it will not work because it is the Swift 2 function:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// code
}
You must update to Swift 3 "prepare" function for it to work for segues:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// code
}
When hooking up an automatic segue for a table view, there is, in addition to Amro's answer (not assigning your corresponding subclass), another two cases where prepareForSegue might not be called. Ensure you've:
hooked up the segue from the table view prototype cell, not the table view controller.
used a segue from under the "Selection Segue" group in the segue connection pop-up menu, not one under "Accessory Action".
[Click image to enlarge]
Whether its an Modal or Push Segue below code will always be called
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"Create Label"]) {
SignUpViewController *asker = segue.destinationViewController;
}
}
I had a similar problem with UICollectionViewCell as the source of segue.
It seems that for the storyboard segue to work (without performSegueWithIdentifier) it's required that you have a custom subclass of UICollectionViewCell, and use it as a Class for the CollectionViewCell on the story board.
I had a similar issue.
The thought process was:
make sure you have the correct method signature. It has changed in Swift 3.
Then make sure the way you have hooked up the button (or whatever that triggers the segue) matches with the way you have hooked the segue in storyboard. Sometimes you call a button, but haven't properly hooked up the segue from that button to the destination viewcontroller.
Be sure the identifier of the segue is correct. Though this isn't the reason the prepareForSegue doesn't get called, this only the reason that a specific segue isn't called.
In my case, it ocured because my controller was extending another controller (Eureka Form View Controller = FormViewController) witch has implemented the performSegue function like this:
open override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// code
}
My function was implemented like this:
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// code
}
To solve this, i just added override before:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// code
}
Voila!
In my case, I did not set the module under the name of the class in the storyboard of the view controller that contains the segue. It was set to none and once I clicked in the module field it set to the correct project / module and resolved the issue.
In my case, I have a base class for several view controllers in my project. That base class has an implementation of prepareForSegue() which wasn't getting called in every case. The problem was that in one of my view controllers that inherits from the base class and overrides its prepareForSegue() implementation, I forgot to call super.prepareForSegue().
Firstly you have to select on your button + ctrl drag item to you view controller choose selection segue .Later, you have to name segue identifier properly.
Don't connect to one view controller to other view controller.
import UIKit.framework for this
Then this method will get called.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"identifierName"])
{
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
ExampleViewController *destViewController = segue.destinationViewController;
}
}