How to segue programmatically in iOS using Swift
Solution 1
If your segue exists in the storyboard with a segue identifier between your two views, you can just call it programmatically using:
performSegue(withIdentifier: "mySegueID", sender: nil)
For older versions:
performSegueWithIdentifier("mySegueID", sender: nil)
You could also do:
presentViewController(nextViewController, animated: true, completion: nil)
Or if you are in a Navigation controller:
self.navigationController?.pushViewController(nextViewController, animated: true)
Solution 2
If your segue exists in the storyboard with a segue identifier between your two views, you can just call it programmatically using
self.performSegueWithIdentifier("yourIdentifierInStoryboard", sender: self)
If you are in Navigation controller
let viewController = YourViewController(nibName: "YourViewController", bundle: nil)
self.navigationController?.pushViewController(viewController, animated: true)
I will recommend you for second approach using navigation controller.
Solution 3
You can use NSNotification
Add a post method in your custom class:
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
Add an observer in your ViewController:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOFReceivedNotication:", name:"NotificationIdentifier", object: nil)
Add function in you ViewController:
func methodOFReceivedNotication(notification: NSNotification){
self.performSegueWithIdentifier("yourIdentifierInStoryboard", sender: self)
}
Solution 4
You can use segue like this:
self.performSegueWithIdentifier("push", sender: self)
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "push" {
}
}
Solution 5
Swift 3 - Also works with SpriteKit
You can use NSNotification.
Example:
1.) Create a segue in the storyboard and name the identifier "segue"
2.) Create a function in the ViewController you are segueing from.
func goToDifferentView() {
self.performSegue(withIdentifier: "segue", sender: self)
}
3.) In the ViewDidLoad() of your ViewController you are segueing from create the observer.
NotificationCenter.default.addObserver(self, selector: #selector(goToDifferentView), name: "segue" as NSNotification.Name, object: nil)
Update -
Last time I used this I had to change the .addObserver
call to the following code to silence the errors.
NotificationCenter.default.addObserver(self, selector: #selector(goToDifferentView), name: NSNotification.Name(rawValue: "segue"), object: nil)
4.) In the ViewController or Scene you are segueing to, add the Post Method wherever you want the segue to be triggered.
NotificationCenter.default.post(name: "segue" as NSNotification.Name, object: nil)
Update -
Last time I used this I had to change the .post
call to the following code to silence the errors.
NotificationCenter.default.post(NSNotification(name: NSNotification.Name(rawValue: "segue"), object: nil) as Notification)
Related videos on Youtube
Shlomi Schwartz
Updated on December 21, 2021Comments
-
Shlomi Schwartz over 2 years
I'm creating an app that uses the Facebook SDK to authenticate users. I'm trying to consolidate the facebook logic in a separate class. Here is the code (stripped for simplicity):
import Foundation class FBManager { class func fbSessionStateChane(fbSession:FBSession!, fbSessionState:FBSessionState, error:NSError?){ //... handling all session states FBRequestConnection.startForMeWithCompletionHandler { (conn: FBRequestConnection!, result: AnyObject!, error: NSError!) -> Void in println("Logged in user: \n\(result)"); let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let loggedInView: UserViewController = storyboard.instantiateViewControllerWithIdentifier("loggedInView") as UserViewController loggedInView.result = result; //todo: segue to the next view??? } } }
I'm using the above class method to check session state changes, and it works fine.
Q: Once I have the user's data, how can I segue to the next view from within this custom class?
Just to be clear, I have a segue with identifier on the storyboard, and I'm trying to find a way to perform a segue from a class which is not the view controller
-
HAS over 9 yearsLike
performSegue:
? -
Shlomi Schwartz over 9 yearsYes, but the code is not in the viewController, how can I achive this?
-
HAS over 9 yearsWell, in that case you should delegate that work (the segueing) from the object you do the work in to the view controller (via a completion block or a delegate method).
-
Chris Hayes about 8 yearsgetting a non nil layout exception
-
-
Shlomi Schwartz over 9 yearsThanks for the reply, how can I call performSegueWithIdentifier from a custom class which is not the view?
-
Shlomi Schwartz over 9 yearsThanks for the reply, however performSegueWithIdentifier is a viewController method, and my code runs in an external class
-
iamprem about 9 yearsIf i use your second method. How to pass data to the next view?
-
Lloyd Sargent about 9 yearsYou would use func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) and set the properties.
-
GajananB over 8 yearsNote when calling performSequeWithIdentifer(), an implementation of prepareForSeque() in your calling controller will be called and you can do various data passing there - in fact, the sender parameter received in prepareForSeque() is simply what is passed to the sender parameter in performSequeWithIdentifier()
-
Chris Hayes about 8 yearsgetting a non nil layout exception
-
scaryguy almost 8 yearsWhat if the segue does not exist in the storyboard? For example, if you want to create a segue to ViewController itself?
-
mfaani over 7 yearsI think after Mohit's edit the answer has became confusing. Assuming that
mySegueID
is pointing to some viewController inside StoryBoard...it would work with or without having a class in its identity inspector.If it's not pointing to a class then the viewController would be not having any specific functionality other than what you see in the storyboard itself. If you give it a class then it would benefit from what ever functionality the class has inside it. But if you just dopresentViewController
orpushViewController
WITHOUT pointing to any viewController's storyboard ID -
mfaani over 7 yearsthen you won't get anything from storyboard, you would just get what's written in the code. So if you want to have both ie functionality of written code + views & outlets from your storyboard then you must do something like the answer in this link ie you MUST 1) link viewController to class in storyboard 2) use instantiateViewControllerWithIdentifier to be able to get whatever you did in storyboard and (since you already did step 1 you would also have functionality from code) 3) then do your push or present.
-
mfaani over 7 years@scaryguy see my comments @@Jerome, I didn't make the edit myself, because I thought it would get rejected because of deviation from original author ... so please edit if you agree
-
Michael Samoylov over 7 yearsSwift 3:
NotificationCenter.default.addObserver(self, selector: #selector(goToDifferentView), name: NSNotification.Name(rawValue: "segue"), object: nil)
-
Maxim over 7 years@iamprem We can use method
optional public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool)
of the Navigation Controller you are pushing another UIViewController on. Note the Navigation Controller needs to be a delegate to invoke that method, meaning inside the Navigation Controller's vieDidLoad() we need to write: self.delegate = self. -
etayluz over 7 yearsWhat in the world is nextViewController ?? I'm getting unresolved identifier
-
Bishan over 7 yearsPerfect! This fixed my issue! 1+
-
Ryan almost 5 yearsIf I am using storyboards, is it better practice to create a segue and use performSegueWithIdentifier or just use presentViewController?
-
uliwitness over 4 yearsPlease do not abuse notifications like this. Use a delegate and make the connection between the view controller and your class explicit. It is near-impossible to observe the control flow of a notification, because there could be multiple subscribers, and instances can subscribe/unsubscribe at will.
-
Rajneesh071 almost 4 yearsself.performSegue(withIdentifier: "yourIdentifierInStoryboard", sender: self)