IOS - 如何使用swift以编程方式进行segue
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27604192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IOS - How to segue programmatically using swift
提问by Shlomi Schwartz
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):
我正在创建一个使用 Facebook SDK 对用户进行身份验证的应用程序。我正在尝试将 facebook 逻辑合并到一个单独的类中。这是代码(为简单起见,已删除):
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?
问:一旦我有了用户的数据,我如何从这个自定义类中转到下一个视图?
EDIT: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
编辑:为了清楚起见,我在情节提要上有一个带有标识符的 segue,我正在尝试找到一种方法来从不是视图控制器的类中执行 segue
回答by Jér?me
If your segue exists in the storyboard with a segue identifier between your two views, you can just call it programmatically using:
如果您的 segue 存在于故事板中,并且您的两个视图之间有一个 segue 标识符,您可以使用以下方法以编程方式调用它:
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)
回答by Rodrigo Otero
You can use NSNotification
您可以使用NSNotification
Add a post method in your custom class:
在自定义类中添加 post 方法:
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
Add an observer in your ViewController:
在您的 ViewController 中添加一个观察者:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOFReceivedNotication:", name:"NotificationIdentifier", object: nil)
Add function in you ViewController:
在您的 ViewController 中添加功能:
func methodOFReceivedNotication(notification: NSNotification){
self.performSegueWithIdentifier("yourIdentifierInStoryboard", sender: self)
}
回答by Manish Mahajan
If your segue exists in the storyboard with a segue identifier between your two views, you can just call it programmatically using
如果您的 segue 存在于故事板中,并且您的两个视图之间有一个 segue 标识符,则您可以使用编程方式调用它
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.
我会推荐你使用导航控制器的第二种方法。
回答by Rudra
You can use segue like this:
您可以像这样使用 segue:
self.performSegueWithIdentifier("push", sender: self)
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "push" {
}
}
回答by Timmy Sorensen
Swift 3- Also works with SpriteKit
Swift 3-也适用于 SpriteKit
You can use NSNotification.
您可以使用NSNotification。
Example:
例子:
1.) Create a segue in the storyboard and name the identifier "segue"
1.) 在故事板中创建一个 segue 并将标识符命名为“segue”
2.) Create a function in the ViewController you are segueing from.
2.) 在您要从中分离的 ViewController 中创建一个函数。
func goToDifferentView() {
self.performSegue(withIdentifier: "segue", sender: self)
}
3.) In the ViewDidLoad() of your ViewController you are segueing from create the observer.
3.) 在您的 ViewController 的 ViewDidLoad() 中,您正在创建观察者。
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.
更新- 上次我使用它时,我不得不更改.addObserver
对以下代码的调用以消除错误。
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.
4.) 在您要转场的 ViewController 或场景中,在您希望触发转场的任何位置添加 Post 方法。
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.
更新- 上次我使用它时,我不得不更改.post
对以下代码的调用以消除错误。
NotificationCenter.default.post(NSNotification(name: NSNotification.Name(rawValue: "segue"), object: nil) as Notification)
回答by Bill
What you want to do is really important for unit testing. Basically you need to create a small local function in the view controller. Name the function anything, just include the performSegueWithIndentifier
.
你想要做什么对于单元测试来说真的很重要。基本上你需要在视图控制器中创建一个小的本地函数。将函数命名为任何名称,只需包含performSegueWithIndentifier
.
func localFunc() {
println("we asked you to do it")
performSegueWithIdentifier("doIt", sender: self)
}
Next change your utility class FBManager
to include an initializer that takes an argument of a function and a variable to hold the ViewController's function that performs the segue.
接下来更改您的实用程序类FBManager
以包含一个初始化程序,该初始化程序接受一个函数的参数和一个变量来保存执行转场的 ViewController 的函数。
public class UtilClass {
var yourFunction : () -> ()
init (someFunction: () -> ()) {
self.yourFunction = someFunction
println("initialized UtilClass")
}
public convenience init() {
func dummyLog () -> () {
println("no action passed")
}
self.init(dummyLog)
}
public func doThatThing() -> () {
// the facebook login function
println("now execute passed function")
self.yourFunction()
println("did that thing")
}
}
(The convenience init allows you to use this in unit testing without executing the segue.)
(便利的 init 允许您在单元测试中使用它而无需执行 segue。)
Finally, where you have //todo: segue to the next view???, put something along the lines of:
最后,在你有 //todo: segue to the next view??? 的地方,放一些东西:
self.yourFunction()
In your unit tests, you can simply invoke it as:
在您的单元测试中,您可以简单地调用它:
let f = UtilClass()
f.doThatThing()
where doThatThing is your fbsessionstatechange and UtilClass
is FBManager.
其中 doThatThing 是您的 fbsessionstatechange 并且UtilClass
是 FBManager。
For your actual code, just pass localFunc
(no parenthesis) to the FBManager class.
对于您的实际代码,只需将localFunc
(无括号)传递给 FBManager 类。
回答by amdan
This worked for me.
这对我有用。
First of all give the view controller in your storyboard a Storyboard ID inside the identity inspector. Then use the following example code (ensuring the class, storyboard name and story board ID match those that you are using):
首先,在身份检查器中为故事板中的视图控制器提供故事板 ID。然后使用以下示例代码(确保类、故事板名称和故事板 ID 与您正在使用的匹配):
let viewController:
UIViewController = UIStoryboard(
name: "Main", bundle: nil
).instantiateViewControllerWithIdentifier("ViewController") as UIViewController
// .instantiatViewControllerWithIdentifier() returns AnyObject!
// this must be downcast to utilize it
self.presentViewController(viewController, animated: false, completion: nil)
For more details see http://sketchytech.blogspot.com/2012/11/instantiate-view-controller-using.htmlbest wishes
有关更多详细信息,请参阅http://sketchytech.blogspot.com/2012/11/instantiate-view-controller-using.html最良好的祝愿
回答by aphoe
Another option is to use modal segue
另一种选择是使用模态转场
STEP 1:Go to the storyboard, and give the View Controller a Storyboard ID. You can find where to change the storyboard ID in the Identity Inspector on the right.
Lets call the storyboard ID ModalViewController
第 1步:转到故事板,并给视图控制器一个故事板 ID。您可以在右侧的身份检查器中找到更改情节提要 ID 的位置。让我们调用故事板 IDModalViewController
STEP 2:Open up the 'sender' view controller (let's call it ViewController
) and add this code to it
第 2 步:打开“sender”视图控制器(我们称之为ViewController
)并将此代码添加到其中
public class ViewController {
override func viewDidLoad() {
showModalView()
}
func showModalView() {
if let mvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ModalViewController") as? ModalViewController {
self.present(mvc, animated: true, completion: nil)
}
}
}
Note that the View Controller we want to open is also called ModalViewController
注意我们要打开的View Controller也叫 ModalViewController
STEP 3:To close ModalViewController, add this to it
第 3步:要关闭 ModalViewController,将其添加到其中
public class ModalViewController {
@IBAction func closeThisViewController(_ sender: Any?) {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
}
回答by Jayprakash Dubey
回答by Jayprakash Dubey
This worked for me:
这对我有用:
//Button method example
@IBAction func LogOutPressed(_ sender: UIBarButtonItem) {
do {
try Auth.auth().signOut()
navigationController?.popToRootViewController(animated: true)
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}
}