I am a beginner.
I have linked two view controllers together with a segue (push). How do I now trigger that push, so it transitions from one view to another? There was no method added in my implementation file which I find weird as it does happen when I create a button or alike.
first you need to go to the storyboard file, select segue and give it an identifier
then in your UIViewController call:
performSegue(withIdentifier: "account", sender: nil)
When you took the segue in your storyboard, you must have given an idenfier so put that identifier here in the perform segue with identifier. And you are done.
#IBAction func nextVC(sender: AnyObject) {
performSegueWithIdentifier("nextVC", sender: sender)
}
Put this code on the button action on which you want to segue your next ViewController. Hope it helps.
Related
Using storyboard this is very easy. You just drag the action to "Exit". But how should I call it from my code?
Create a manual segue (ctrl-drag from File’s Owner to Exit),
Choose it in the Left Controller Menu below green EXIT button.
Insert Name of Segue to unwind.
Then,- (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender. with your segue identify.
Here's a complete answer with Objective C and Swift:
1) Create an IBAction unwind segue in your destination view controller (where you want to segue to). Anywhere in the implementation file.
// Objective C
- (IBAction)unwindToContainerVC:(UIStoryboardSegue *)segue {
}
// Swift
#IBAction func unwindToContainerVC(segue: UIStoryboardSegue) {
}
2) On the source view controller (the controller you're segueing from), ⌃ + drag from "Name of activity" to exit. You should see the unwind segue created in step 1 in the popup. (If you don't see it, review step one). Pick unwindToContainerVC: from the popup, or whatever you named your method to connect your source controller to the unwind IBAction.
3) Select the segue in the source view controller's document outline of the storyboard (it will be listed near the bottom), and give it an identifier.
4) Call the unwind segue using this method from source view controller, substituting your unwind segue name.
// Objective C
[self performSegueWithIdentifier:#"unwindToContainerVC" sender:self];
// Swift
self.performSegueWithIdentifier("unwindToContainerVC", sender: self)
NB. Use the sourceViewController property of the segue parameter on the unwind method to access any exposed properties on the source controller. Also, notice that the framework handles dismissing the source controller. If you'd like to confirm this add a dealloc method to the source controller with a log message that should fire once it has been killed. If dealloc doesn't fire you may have a retain cycle.
bradleygriffith's answer was great. I took step 10 and made a screenshot for simplification. This is a screenshot in Xcode 6.
Control-drag from the orange icon to the red Exit icon to create an unwind without any actions/buttons in the view.
Then select the unwind segue in the sidebar:
Set a Segue Identifier string:
Access that identifier from code:
[self performSegueWithIdentifier:#"unwindIdentifier" sender:self];
I used [self dismissViewControllerAnimated: YES completion: nil]; which will return you to the calling ViewController.
Quoting text from Apple's Technical Note on Unwind Segue:
To add an unwind segue that will only be triggered programmatically, control+drag from the scene's view controller icon to its exit icon, then select an unwind action for the new segue from the popup menu.
Link to Technical Note
Vishal Chaudhry's answer above worked for me. I would also add that in order to manually trigger the seque using:
[self performSegueWithIdentifier:#"mySegueName" sender:self];
from within the ViewController you must also select the unwind segue under the ViewController's Scene in the storyboard and in the properties view on the RHS ensure that the Indentifier field contains the namer you're referring to in the code ("mySegueName" in the example above).
If you omit this step, the line above will throw an exception that the seque name is not known.
SWIFT 4:
1. Create an #IBAction with segue inside controller you want to unwind to:
#IBAction func unwindToVC(segue: UIStoryboardSegue) {
}
2. In the storyboard, from the controller you want to segue (unwind) from ctrl+drag from the controller sign to exit sign and choose method you created earlier:
3. Now you can notice that in document outline you have new line with title "Unwind segue....". Now you should click on this line and open attribute inspector to set identifier (in my case unwindSegueIdentifier).
4. You're almost done! Now you need to open view controller you wish to unwind from and create some method that will perform segue. For example you can add button, connect it with code with #IBAction, after that inside this IBAction add perfromSegue(withIdentifier:sender:) method:
#IBAction func unwindToSomeVCWithSegue(_ sender: UIButton) {
performSegue(withIdentifier: "unwindSegueIdentifier", sender: nil)
}
So that is all you have to do!
Swift 4.2, Xcode 10+
For those wondering how to do this with VCs not set up via the storyboard (those coming to this question from searching "programmatically" + "unwind segue").
Given that you cannot set up an unwind segue programatically, the simplest solely programmatic solution is to call:
navigationController?.popToRootViewController(animated: true)
which will pop all view controllers on the stack back to your root view controller.
To pop just the topmost view controller from the navigation stack, use:
navigationController?.popViewController(animated: true)
Backwards compatible solution that will work for versions prior to ios6, for those interested:
- (void)unwindToViewControllerOfClass:(Class)vcClass animated:(BOOL)animated {
for (int i=self.navigationController.viewControllers.count - 1; i >= 0; i--) {
UIViewController *vc = [self.navigationController.viewControllers objectAtIndex:i];
if ([vc isKindOfClass:vcClass]) {
[self.navigationController popToViewController:vc animated:animated];
return;
}
}
}
FYI: In order for #Vadim's answer to work with a manual unwind seque action called from within a View Controller you must place the command:
[self performSegueWithIdentifier:(NSString*) identifier sender:(id) sender];
inside of the overriden class method viewDidAppear like so:
-(void) viewDidAppear:(BOOL) animated
{
[super viewDidAppear: animated];
[self performSegueWithIdentifier:#"SomeSegueIdentifier" sender:self];
}
If you put it in other ViewController methods like viewDidLoad or viewWillAppear it will be ignored.
My issue is that I have two view controllers, and I need to transfer a string from one view controller to the next. I already have that down from a segue. The actual issue is that I need a label to change in the next view controller to make it match the currentTitle of the button in the previous view. And yes, there are multiple buttons.
My code from view 1 is this:
#IBAction func whichButtonWasClicked(sender: AnyObject) {
clickedButton = sender.currentTitle!!
}
// Segue - Pass the Data of which lesson was chosen
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let DestViewController : Lesson = segue.destinationViewController as! Lesson
DestViewController.lessonPlan = clickedButton
}
I connected all my 7 buttons to that same one action.
The problem is that when I transfer view controllers, and do...
print(lessonPlan)
It does not give me the title of the button from the action, because I guess that action is after the segue. And yes I tested it, and it IS after the segue. SO it does work, it's just a bit delayed, and I need it to be a part of the segue.
Since your IBAction is being called after prepareForSegue, you can use programmatic segues.
Right now, you're probably dragging a segue from your button to the next view controller. Instead, you can drag a segue from the current view controller to the next one (see this answer for a visual guide). This will create a programmatic segue that you can trigger whenever you'd like from code. Remember to give the segue an identifier in Xcode.
Then in whichButtonWasClicked, call self.performSegueWithIdentifier("identifier you setin Xcode", sender: sender) after you set clickedButton in order to trigger the segue. By doing so, you'll ensure that your button action is called before the segue starts.
I use a push segue to transition from a uisearchcontroller located within my root view controller, to a second view controller. When I try to use an unwind segue method to transition back to the root view controller from my second view controller, my app does not transition unless the button connected to the unwind method is pressed twice. The unwind method is called both times, however the transition only occurs upon the second call. I do not know why this occurs. Any help is appreciated. Thanks!
Unwind segue method
#IBAction func saveWordAndDefinition(segue:UIStoryboardSegue) {
self.searchController.active = false
if let definitionViewController = segue.sourceViewController as? DefinitionViewController {
saveWordToCoreData(definitionViewController.word)
}
tableView.reloadData()
}
How I linked my segue
Unwind segue
While what you're doing is permissible, it seems to be against best practice. The functionality of presenting a view controller, UITableViewController in this case, entering information, then later dismissing it with a button in the upper-right hand corner is generally associated with a modal view. In a push segue you'll get the back button in the upper-left corner for free, which will enable to you to pop the view controller off the stack without writing extra code.
Here's another Stack Overflow question that describe: What is the difference between Modal and Push segue in Storyboards?
To answer your question specifically, here are a couple links that should help:
[self.navigationController popViewControllerAnimated:YES]; is probably what you're looking for.
Dismiss pushed view from within Navigation Controller
How can I dismiss a pushViewController in iPhone/iPad?
So here's how I finally got this to work:
In my FirstViewController (the vc i'm unwinding to):
Here is my unwind segue method.
#IBAction func saveWordAndDefinition(segue:UIStoryboardSegue) {
self.navigationController?.popViewControllerAnimated(false)
}
Then I gave my unwind segue the identifier "unwind" in Storyboard.
In my SecondViewController (the vc i'm unwinding from):
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "unwind" {
if let destination = segue.destinationViewController as? VocabListViewController {
destination.saveWordToCoreData(word)
destination.tableView.reloadData()
}
}
}
I took care of passing data in the prepareForSegue method of my SecondViewController. Thanks to #Lory Huz for the suggestion. I finally figured out what you meant by it.
Works without any errors!
Im using StoryBoard and i am not so sure how to instantiate a ViewController or how to reference one.
The thing is i have two view controllers and i have one with a button. I want to go to the other view controller when i pressed the button from the first view controller.
I have tried something like that:
let secondViewController:UIViewController = UIViewController()
self.presentViewController(secondViewController, animated: true, completion: nil)
Does anyone knows how to explain it to me? Thanks!
There are couple of ways of navigating between view controllers. Here's how you do it in code without segues if you're going that way.
Presenting a view controller modally.
Say you have 2 view controller scenes in the storyboard, FirstViewController and SecondViewController. You want to transit from FirstViewController to SecondViewController and there is no segue between them.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyboard.instantiateViewControllerWithIdentifier("SecondVC") as UIViewController
presentViewController(secondViewController, animated: true, completion: nil)
The important part is the that you have to assign an identifier to the view controller you want to go. In this case its the SecondViewController. The way you assign an identifier is you select the view controller, open up the right panel and in it, go to the Identity Inspector (the third one from the left) and under the Identity, assign an identifier to the Storyboard ID field. I put mine as SecondVC as you can see from the code snippet above.
Push to another view controller.
If you want to push on to another view controller instead of presenting it, all you have to do is embed the FirstViewController in a UINavigationController and change the code to this.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyboard.instantiateViewControllerWithIdentifier("SecondVC") as UIViewController
navigationController?.pushViewController(secondViewController, animated: true)
In a comment of yours I saw you want to go to the next view controller based on a condition. Well all you have to do is check your condition in a if else statement and execute either of those above code.
Using Segues.
If you're going to use segues instead of code, here's how you do it.
In the storyboard first you select the button and Ctrl drag to the other view controller. You'll be prompted to choose between different segues. Select show for push or show detail for modal transition (I've explained what these are below). And that's it! If you run it and tap the button, you'd be taken to the other view controller.
But if you want more control over this, you have to do a little more work.. Instead of creating a segue directly from the button, select your view controller and select that little yellow icon on top (This is in Xcode 6. In older Xcode versions its under the view controller scene). Ctrl drag from that icon to the other view controller you want to transit to. You can see a connection appears between those two controllers. Select the segue and open up the right panel and go to the Attributes Inspector (The forth one from the left). Give a name to the field identifier. I gave ToSecond.
Now create a normal action from the button. And you have to call a method called performSegueWithIdentifier passing that identifier. What it does is basically execute a segue with the identifier we give.
#IBAction func segueButtonPressed(sender: UIButton) {
performSegueWithIdentifier("ToSecond", sender: nil)
}
And this would work. You can do the conditions checking here inside a if else and if the conditions are met, call performSegueWithIdentifier.
One other thing you're likely to face is having multiple buttons in a view controller and segueing to different view controller when you tap each of them. A method called prepareForSegue fires each time a segue happens. And inside it, you can check for current segue identifier and execute it. The below code snippet will make this clearer.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ToSecond" {
let secondViewController = segue.destinationViewController as SecondViewController
}
}
Another thing I'd like to mention is that presentViewController and pushViewController are deprecated from iOS8. Instead you can use showDetailViewController for modal and showViewController to push.
showDetailViewController(secondViewController, sender: nil)
navigationController?.showViewController(secondViewController, sender: nil)
I'm not sure if these are backwards compatible. Meaning using show and show detail will work if you're developing for iOS 7 as well. If you are then just stick with the older methods.
First set seques of uistoryboardviewcontroller and try this
self.performSegueWithIdentifier("push", sender: self)
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "push" {
}
In the storyboard, select VC1 and then select the button and press control and while holding down the left button or touchpad drag across to your VC2. Then a menu should pop up. Select modal.
Run and Test. It should now perform a transition.
To transition back, the easiest way is to embed VC1 in a Navigation Controller. To do this, zoom out, select VC1 and go to the top of the screen and select:
Editor > Embed > Navigation View Controller.
Now test and run. You should have the option to go back.
If you are binding view controller programmatically you need to follow this step if you are creating storyboard based application.
It is similar what we don in Objective-c just the syntax has changed.
According to your question what you need to do is go to Main.storyboard and need to select identity inspector.
There you will be able to view identity which contains two fields
1.) Storyboard ID
2.) Restoration ID
Give them the name of view controller you have binded with class in storyboard id and select check box below restoration id. It will automatically copy storyboard ID in restoration ID.
You need to do same for all your view controllers.
let secondView = self.storyboard?.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController
self.presentViewController(secondView, animated: true, completion: nil)
you need to write the name you have entered in Storyboard ID for self.storyboard?.instantiateViewControllerWithIdentifier("/* Storyboard ID */")
You can also visit the link:
Instantiate and Present a viewController in Swift
okay,
in interface builder control click on your button and drag the blue line that appears to the second view controller. The second view controller will highlight blue. You can release and the button is connected. In the popup menu select "modal segue". No code necessary. XCODE handles it.
Watch this video for a demo.
Using storyboard this is very easy. You just drag the action to "Exit". But how should I call it from my code?
Create a manual segue (ctrl-drag from File’s Owner to Exit),
Choose it in the Left Controller Menu below green EXIT button.
Insert Name of Segue to unwind.
Then,- (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender. with your segue identify.
Here's a complete answer with Objective C and Swift:
1) Create an IBAction unwind segue in your destination view controller (where you want to segue to). Anywhere in the implementation file.
// Objective C
- (IBAction)unwindToContainerVC:(UIStoryboardSegue *)segue {
}
// Swift
#IBAction func unwindToContainerVC(segue: UIStoryboardSegue) {
}
2) On the source view controller (the controller you're segueing from), ⌃ + drag from "Name of activity" to exit. You should see the unwind segue created in step 1 in the popup. (If you don't see it, review step one). Pick unwindToContainerVC: from the popup, or whatever you named your method to connect your source controller to the unwind IBAction.
3) Select the segue in the source view controller's document outline of the storyboard (it will be listed near the bottom), and give it an identifier.
4) Call the unwind segue using this method from source view controller, substituting your unwind segue name.
// Objective C
[self performSegueWithIdentifier:#"unwindToContainerVC" sender:self];
// Swift
self.performSegueWithIdentifier("unwindToContainerVC", sender: self)
NB. Use the sourceViewController property of the segue parameter on the unwind method to access any exposed properties on the source controller. Also, notice that the framework handles dismissing the source controller. If you'd like to confirm this add a dealloc method to the source controller with a log message that should fire once it has been killed. If dealloc doesn't fire you may have a retain cycle.
bradleygriffith's answer was great. I took step 10 and made a screenshot for simplification. This is a screenshot in Xcode 6.
Control-drag from the orange icon to the red Exit icon to create an unwind without any actions/buttons in the view.
Then select the unwind segue in the sidebar:
Set a Segue Identifier string:
Access that identifier from code:
[self performSegueWithIdentifier:#"unwindIdentifier" sender:self];
I used [self dismissViewControllerAnimated: YES completion: nil]; which will return you to the calling ViewController.
Quoting text from Apple's Technical Note on Unwind Segue:
To add an unwind segue that will only be triggered programmatically, control+drag from the scene's view controller icon to its exit icon, then select an unwind action for the new segue from the popup menu.
Link to Technical Note
Vishal Chaudhry's answer above worked for me. I would also add that in order to manually trigger the seque using:
[self performSegueWithIdentifier:#"mySegueName" sender:self];
from within the ViewController you must also select the unwind segue under the ViewController's Scene in the storyboard and in the properties view on the RHS ensure that the Indentifier field contains the namer you're referring to in the code ("mySegueName" in the example above).
If you omit this step, the line above will throw an exception that the seque name is not known.
SWIFT 4:
1. Create an #IBAction with segue inside controller you want to unwind to:
#IBAction func unwindToVC(segue: UIStoryboardSegue) {
}
2. In the storyboard, from the controller you want to segue (unwind) from ctrl+drag from the controller sign to exit sign and choose method you created earlier:
3. Now you can notice that in document outline you have new line with title "Unwind segue....". Now you should click on this line and open attribute inspector to set identifier (in my case unwindSegueIdentifier).
4. You're almost done! Now you need to open view controller you wish to unwind from and create some method that will perform segue. For example you can add button, connect it with code with #IBAction, after that inside this IBAction add perfromSegue(withIdentifier:sender:) method:
#IBAction func unwindToSomeVCWithSegue(_ sender: UIButton) {
performSegue(withIdentifier: "unwindSegueIdentifier", sender: nil)
}
So that is all you have to do!
Swift 4.2, Xcode 10+
For those wondering how to do this with VCs not set up via the storyboard (those coming to this question from searching "programmatically" + "unwind segue").
Given that you cannot set up an unwind segue programatically, the simplest solely programmatic solution is to call:
navigationController?.popToRootViewController(animated: true)
which will pop all view controllers on the stack back to your root view controller.
To pop just the topmost view controller from the navigation stack, use:
navigationController?.popViewController(animated: true)
Backwards compatible solution that will work for versions prior to ios6, for those interested:
- (void)unwindToViewControllerOfClass:(Class)vcClass animated:(BOOL)animated {
for (int i=self.navigationController.viewControllers.count - 1; i >= 0; i--) {
UIViewController *vc = [self.navigationController.viewControllers objectAtIndex:i];
if ([vc isKindOfClass:vcClass]) {
[self.navigationController popToViewController:vc animated:animated];
return;
}
}
}
FYI: In order for #Vadim's answer to work with a manual unwind seque action called from within a View Controller you must place the command:
[self performSegueWithIdentifier:(NSString*) identifier sender:(id) sender];
inside of the overriden class method viewDidAppear like so:
-(void) viewDidAppear:(BOOL) animated
{
[super viewDidAppear: animated];
[self performSegueWithIdentifier:#"SomeSegueIdentifier" sender:self];
}
If you put it in other ViewController methods like viewDidLoad or viewWillAppear it will be ignored.