I'm using storyboard, and in my storyboard I got a button which I connected with another view controller. So when you click the button, the other view controller shows up. I connected this using an Action Segue - Push in the storyboard. I also connected the button with an IBAction property. The problem is when I click the button it first goes to the view controller that its connected to, and after that it executes the IBAction function. How can I change this order?
You cannot change that order. There are two things that you can do.
First:
Use the segue only.
Overwrite prepareForSegue: and place your code there. If there is more than one segure from that view controller then you can distinguish within prepareForSegue: which one is currently being performed. For that you should provide them with unique names/segue IDs.
Second:
Use the IBAction only.
Within the IBAction method, at its very end, call performSegueWithIdentifier:sender:. Again, for that you will have to name all your segues with unique segue IDs.
The question to ask yourself is, why are you using both? Pick one and stick with it IMO.
If you want to perform some actions when the segue happens you should implement
prepareForSegue:
Update to address comment
I actually don't know how I can do it in code, how can I load a ViewController that is on my storyboard without using the Action Segue Push?
The easiest way that I've found is in your Storyboard you can set an identifier for the view controller.
Notice Storyboard ID is set to MyViewController
Now in your IBAction method you can do the following.
UIViewController *myViewController = [[UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:#"MyViewController"];
[self presentViewController:myViewController animated:YES completion:nil];
I solved this by chaining the IBAction from my segue. I find this approach the most useful as I can have a "save" action without a segue (chain a button to the IBAction, sometimes useful), and also use a segue for dismissing the view controller when necessary.
-(IBAction)save:(id)sender
{
/* Do some Save stuff */
}
Then in my prepareForSegue:sender:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"save"])
{
[self save:sender];
}
}
Link up your non-segue buttons to the IBAction, and segue your unwind or other such buttons with an identifier as "save". Magic.
Related
I have a ViewControllerA that has roughly 15 buttons in my case they represent levels, When a level is pressed it segues to ViewControllerB. Now it doesn't make sense to manually ctrl+drag and create segue for each button. I'm wondering how can a button segue to ViewControllerB and have a unique identifier then ill be passing an object in other words data to ViewControllerB to recognize which level the user pressed. I also want to point out that I have a push view controller.
So far one of my unsuccessful attempts were to do is to ctrl+drag all the buttons and create a method called:(the button title in my case is the level number)
- (IBAction)buttonPressed:(UIButton *)sender {
[self performSegueWithIdentifier:[sender currentTitle] sender:self];
}
afterwards I call the prepareForSegue:segue sender:sender method.To be honest Im new to iOS developing. Any helpful tutorial or article would be great for me.
Thanks in advance for all helpers.
You were close with your unsuccessful attempt. You only want one identifier for a single segue that you set up in IB directly from the controller to VCB. In your action method, that all the button's invoke, do this (notice that I'm passing the button in the sender argument):
- (IBAction)buttonPressed:(UIButton *)sender {
[self performSegueWithIdentifier:#"MySegueIdentifier" sender:sender];
}
Then in prepareForSegue, you can use the sender argument to get the button's title:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UIButton *)sender {
NSString *title = sender.currentTitle;
// do what you need with the title
}
Create a private property on ViewControllerA (perhaps using an enum) to make note of which level is selected.
In your - (IBAction)buttonPressed:(UIButton *)sender method, you need to figure out which button was pressed, and use that information to set the property. Then call [self performSegueWithIdentifier:#"nameOfStoryboardSegue" sender:self];
Create a public property on ViewControllerB to keep track of which level is selected.
Override the prepareForSegue:segue sender:sender method. Instantiate the destination view controller as a ViewControllerB, and set the property on B to match the selected property from A.
Perform the segue.
This question & answer will help you with passing the data between views in the prepareForSegue method, and this question & answers might help with handling all the buttons in the single IBAction method.
I know this is an old question, but I found a simple solution...
duplicate the View Controller from your storyboard and assign the same class to it in identity inspector. You will have a duplicate "storyboard view controller" connected to the same code. With its own icon, tag and storyboard ID
I just need to know how to make some 'conditional' redirect / segue to some view. For example :
If user haven't login yet, then a view with login form appears. But if user logged in already, they will see their profile view.
How to make conditional segue like that using storyboard?
Thank you
For conditional segues, don't start a segue from a button as you normally do.
Instead of that use the following steps:
In your storyboad, start a segue directly from the source view controller to the destination view controller. For doing this, you can drag your source view controller's icon on the bar just below the view to the destination view controller on the main canvas area. Just remember you have to connect two view controllers directly and not with any control.
Enter a suitable segue identifier for this segue. For example say "conditionSegue"
Now, in your source view controller’s .m file perform your condition and call -performSegueWithIdentifier:sender: method on "self" like this:
-(void)loadDestinationVC{
if(condition == YES){
[self performSegueWithIdentifier:#"conditionSegue" sender:nil];
}
}
I hope I made it clear.
I believe a better approach if you want to use segues from buttons would be to use this:
First create a button and use a segue to connect it to another view, give this segue a name
then use this method in your .m file
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender {
if ([identifier isEqualToString:#"SegueName"]) {
//Check if should make the segue
//if not do something
[self doSomething];
//and return NO;
return NO;
}
return YES;
}
In Swift you could do :
as #Gaurav Singh suggested in his answer
Step 1: Insert a segue from ViewControllerA to ViewControllerB. The segue should start from ViewControllerA itself and not from any control ( like Button ) in it.
Step 2: Give segue an unique identifier in storyboard. Ex: seageFromAtoB
Step 3 : In your ViewControllerforA.swift write :
if(condition == true) {
self.performSegueWithIdentifier("seageFromAtoB", sender: self)
}
If you are performing some task in some other Thread then using performSegueWithIdentifier can throw an exception.
If you get this error then you should use :
if(condition==true){
NSOperationQueue.mainQueue().addOperationWithBlock {
self.performSegueWithIdentifier("seageFromAtoB", sender: self)
}
}
This will perform segue redirection in main Thread.
Hope this help for someone looking for Swift option
You make the segues directly from one controller to another (or others), and give them identifiers. In code you call choose between segues depending on your conditions, and call performSegueWithIdentifier:sender:.
Create "generic" segue by ctrl dragging from the view controller icon at the bottom to the destination. This segue won't be associated with any action. Then, in your code where ever the event is using your conditional code that you want to trigger the segue, call:
- (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender
I connected first view controller with the second one using StoryBoard Push Segue and Interface Builder.
The button is named GO on top/right.
I have three textfield that must be filled before going to second controller.
I display an alert when one of them is empty.
The problem is that my code after displaying correct alertView goes to SecondController instead of remaining on mainController.
if ([segue.identifier isEqualToString:#"DataDisplay"])
{
if (![self verifySelection]) {
return;
} else {
RowViewController *rowViewController = segue.destinationViewController;
// rowViewController.delegate = self;
}
}
1) You have a segue wired directly from your Go button to your Sensor Data view controller. You don't want this, because anytime someone touches Go, the segue is going to happen ... no stopping it. So, first step is to remove the segue you have going from Go to your second view controller.
2) Instead, wire the segue from the File's Owner icon below the view controller to the second view controller. Give it a name like DataDisplay.
3) In the IBAction for your Go button
if ([self verifySelection) {
[self performSegueWithIdentifier:#"DataDisplay" sender:self]
}
An easy fix would be to create the segue manually, rather than letting the interface builder manage it. So you would ctrl-drag from your main view controller to your second one, selecting push as the type of segue and assigning it an identifier through the identifier inspector, then you connect an IBAction to your Go button and in the method you perform the checks on the text fields before programmatically firing the segue with:
[self performSegueWithIdentifier:#"whateverIdentifierYouGaveYourSegue" sender:self];
Heads up: to create a manual segue from a viewcontroller to another one, you need to either zoom out in your storyboard or ctrl-drag from the yellow circle underneath the view!
Edit: Your IBAction connected to the button method should be something like the following:
- (IBAction)download:(id)sender {
if(text boxes are ok)
[self performSegueWithIdentifier:#"segueIdentifier" sender:self];
else
[self showWarning];
}
Make sure that you assigned the ID segueIdentifier to the segue you created in your storyboard.
Your problem is you are defining the "performSegueWithIdentifier" after displaying the alert.
I think the code you are doing is like this :
//AlertView Allocation
[alert show];
Perform Segue
If this is how you are doing, then you are doing it wrong.
You have to use the structure of If-Else Statements and put up the Perform Segue in the condition where all the textfields are filled.
I have a view controller with 2 different segues that goes to 2 different view controller,and i have to implement the cancel button in both the controllers.When i press the cancel button,in both the controller,the view will return to the initial view controller.My question is how can i implement the buttons?When i try with this code the compiler warning:Multiple declaration of method "cancel:" found and ignored.Thank you.
interface:
-(IBAction)cancel:(UIStoryboardSegue *)segue;
-(IBAction)done:(UIStoryboardSegue *)segue;
-(IBAction)cancel:(UIStoryboardSegue *)segue;
implementation:
-(IBAction)done:(UIStoryboardSegue *)segue
{
if([[segue identifier] isEqualToString:#"ReturnInput"]){
AddSightingViewController *addController = [segue sourceViewController];
if (addController.birdSighting) {
[self.dataController
addBirdSightingWithSighting:addController.birdSighting];
[[self tableView]reloadData];
}
[self dismissViewControllerAnimated:YES completion:NULL];
}
}
-(IBAction)cancel:(UIStoryboardSegue *)segue
{
if([[segue identifier] isEqualToString:#"CancelInput"]){
[self dismissViewControllerAnimated:YES completion:NULL];
}
}
I'm not sure of what you're trying to do. But I think the cancel method needs to be in the 2 child View Controllers, not in the main one. One for each controller (and one cancel button for each view). That way you won't have any problems with multiple declarations of a method.
From your code I conclude that you are using (or want use) exit segues for canceling.
First, you should only have one method declaration and implementation for your cancel method in the initial view controller. In your storyboard create exit segues by control-dragging from your cancel buttons to the green exit icon blow the view controller and select the cancel method defined in the initial view controller. Do that for both view controllers. You should also give your exit segues different identifiers in your storyboard (you need to select the segue in the Document Outline to change its identifier).
Then your cancel method in your initial view controller can look something like this:
-(IBAction)cancel:(UIStoryboardSegue *)segue
{
if([[segue identifier] isEqualToString:#"CancelInput1"]) {
// Do something
} else if([[segue identifier] isEqualToString:#"CancelInput2"]) {
// Do something different
}
}
If you don't want to do anything when canceling just leave the method empty.
If you wan't to go back you need to implement an unwind segue.
To do this, define a method to go back on the original view controller (the one you want to go back). You can leave the method empty.
- (IBAction)methodName:(UIStoryboardSegue *)segue
{
}
Then on IB ctrl + drag from the button (or from the view controller) to the green "exit" icon. Select the methodName from the popup menu. If you did it from the view controller set the identifier on the segue and call it with performSegueWithIdentifier: from the button action.
Considerations:
The method name will be detected in every view controller on the storyboard.
You can define the same method name in different view controllers, but when you execute the unwind segue, you will go back to the most recent on the navigation path.
I have a common UIViewController that all my UIViewsControllers extend to reuse some common operations.
I want to set up a segue on this "Common" UIViewController so that all the other UIViewControllers inherit.
I am trying to figure out how do I do that programmatically.
I guess that the question could also be how do I set a segue for all my UIViewControllers without going into the story board and do them by hand.
I thought I would add another possibility. One of the things you can do is you can connect two scenes in a storyboard using a segue that is not attached to an action, and then programmatically trigger the segue inside your view controller. The way you do this, is that you have to drag from the file's owner icon at the bottom of the storyboard scene that is the segueing scene, and right drag to the destination scene. I'll throw in an image to help explain.
A popup will show for "Manual Segue". I picked Push as the type. Tap on the little square and make sure you're in the attributes inspector. Give it an identifier which you will use to refer to it in code.
Ok, next I'm going to segue using a programmatic bar button item. In viewDidLoad or somewhere else I'll create a button item on the navigation bar with this code:
UIBarButtonItem *buttonizeButton = [[UIBarButtonItem alloc] initWithTitle:#"Buttonize"
style:UIBarButtonItemStyleDone
target:self
action:#selector(buttonizeButtonTap:)];
self.navigationItem.rightBarButtonItems = #[buttonizeButton];
Ok, notice that the selector is buttonizeButtonTap:. So write a void method for that button and within that method you will call the segue like this:
-(void)buttonizeButtonTap:(id)sender{
[self performSegueWithIdentifier:#"Associate" sender:sender];
}
The sender parameter is required to identify the button when prepareForSegue is called. prepareForSegue is the framework method where you will instantiate your scene and pass it whatever values it will need to do its work. Here's what my method looks like:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"Associate"])
{
TranslationQuizAssociateVC *translationQuizAssociateVC = [segue destinationViewController];
translationQuizAssociateVC.nodeID = self.nodeID; //--pass nodeID from ViewNodeViewController
translationQuizAssociateVC.contentID = self.contentID;
translationQuizAssociateVC.index = self.index;
translationQuizAssociateVC.content = self.content;
}
}
I tested it and it works.
By definition a segue can't really exist independently of a storyboard. It's even there in the name of the class: UIStoryboardSegue. You don't create segues programmatically - it is the storyboard runtime that creates them for you. You can normally call performSegueWithIdentifier: in your view controller's code, but this relies on having a segue already set up in the storyboard to reference.
What I think you are asking though is how you can create a method in your common view controller (base class) that will transition to a new view controller, and will be inherited by all derived classes. You could do this by creating a method like this one to your base class view controller:
- (IBAction)pushMyNewViewController
{
MyNewViewController *myNewVC = [[MyNewViewController alloc] init];
// do any setup you need for myNewVC
[self presentModalViewController:myNewVC animated:YES];
}
and then in your derived class, call that method when the appropriate button is clicked or table row is selected or whatever.
I've been using this code to instantiate my custom segue subclass and run it programmatically. It seems to work. Anything wrong with this? I'm puzzled, reading all the other answers saying it cannot be done.
UIViewController *toViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"OtherViewControllerId"];
MyCustomSegue *segue = [[MyCustomSegue alloc] initWithIdentifier:#"" source:self destination:toViewController];
[self prepareForSegue:segue sender:sender];
[segue perform];
Guess this is answered and accepted, but I just would like to add a few more details to it.
What I did to solve a problem where I would present a login-view as first screen and then wanted to segue to the application if login were correct. I created the segue from the login-view controller to the root view controller and gave it an identifier like "myidentifier".
Then after checking all login code if the login were correct I'd call
[self performSegueWithIdentifier: #"myidentifier" sender: self];
My biggest misunderstanding were that I tried to put the segue on a button and kind of interrupt the segue once it were found.
You have to link your code to the UIStoryboard that you're using. Make sure you go into YourViewController in your UIStoryboard, click on the border around it, and then set its identifier field to a NSString that you call in your code.
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard"
bundle:nil];
YourViewController *yourViewController =
(YourViewController *)
[storyboard instantiateViewControllerWithIdentifier:#"yourViewControllerID"];
[self.navigationController pushViewController:yourViewController animated:YES];
For controllers that are in the storyboard.
jhilgert00 is this what you were looking for?
-(IBAction)nav_goHome:(id)sender {
UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:#"HomeController"];
[self.navigationController pushViewController: myController animated:YES];
}
OR...
[self performSegueWithIdentifier:#"loginMainSegue" sender:self];
well , you can create and also can subclass the UIStoryBoardSegue . subclassing is mostly used for giving custom transition animation.
you can see video of wwdc 2011 introducing StoryBoard. its available in youtube also.
http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIStoryboardSegue_Class/Reference/Reference.html#//apple_ref/occ/cl/UIStoryboardSegue
I'd like to add a clarification...
A common misunderstanding, in fact one that I had for some time, is that a storyboard segue is triggered by the prepareForSegue:sender: method. It is not. A storyboard segue will perform, regardless of whether you have implemented a prepareForSegue:sender: method for that (departing from) view controller.
I learnt this from Paul Hegarty's excellent iTunesU lectures. My apologies but unfortunately cannot remember which lecture.
If you connect a segue between two view controllers in a storyboard, but do not implement a prepareForSegue:sender: method, the segue will still segue to the target view controller. It will however segue to that view controller unprepared.
Hope this helps.
Storyboard Segues are not to be created outside of the storyboard. You will need to wire it up, despite the drawbacks.
UIStoryboardSegue Reference clearly states:
You do not create segue objects directly. Instead, the storyboard
runtime creates them when it must perform a segue between two view
controllers. You can still initiate a segue programmatically using the
performSegueWithIdentifier:sender: method of UIViewController if you
want. You might do so to initiate a segue from a source that was added
programmatically and therefore not available in Interface Builder.
You can still programmatically tell the storyboard to present a view controller using a segue using presentModalViewController: or pushViewController:animated: calls, but you'll need a storyboard instance.
You can call UIStoryboards class method to get a named storyboard with bundle nil for the main bundle.
storyboardWithName:bundle:
First of, suppose you have two different views in storyboard, and you want to navigate from one screen to another, so follow this steps:
1). Define all your views with class file and also storyboard id in identity inspector.
2). Make sure you add a navigation controller to the first view. Select it in the Storyboard and then Editor >Embed In > Navigation Controller
3). In your first class, import the "secondClass.h"
#import "ViewController.h
#import "secondController.h"
4). Add this command in the IBAction that has to perform the segue
secondController *next=[self.storyboard instantiateViewControllerWithIdentifier:#"second"];
[self.navigationController pushViewController:next animated:YES];
5). #"second" is secondview controller class, storyboard id.
I reverse-engineered and made an open source (re)implementation of UIStoryboard's segues: https://github.com/acoomans/Segway
With that library, you can define segues programmatically (without any storyboard).
Hope it may help.
A couple of problems, actually:
First, in that project you uploaded for us, the segue does not bear the "segue1" identifier:
no identifier
You should fill in that identifier if you haven't already.
Second, as you're pushing from table view to table view, you're calling initWithNibName to create a view controller. You really want to use instantiateViewControllerWithIdentifier.
Here is the code sample for Creating a segue programmatically:
class ViewController: UIViewController {
...
// 1. Define the Segue
private var commonSegue: UIStoryboardSegue!
...
override func viewDidLoad() {
...
// 2. Initialize the Segue
self.commonSegue = UIStoryboardSegue(identifier: "CommonSegue", source: ..., destination: ...) {
self.commonSegue.source.showDetailViewController(self.commonSegue.destination, sender: self)
}
...
}
...
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// 4. Prepare to perform the Segue
if self.commonSegue == segue {
...
}
...
}
...
func actionFunction() {
// 3. Perform the Segue
self.prepare(for: self.commonSegue, sender: self)
self.commonSegue.perform()
}
...
}