我正在创建一个使用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???
}
}
}
我正在使用上面的类方法来检查会话状态的变化,它工作得很好。
问:一旦我有了用户的数据,我如何从这个自定义类中segue到下一个视图?
我在storyboard上有一个带标识符的segue,我试图找到一种方法从一个不是视图控制器的类执行segue
如果你的segue存在于故事板中,并且在你的两个视图之间有一个segue标识符,你可以通过编程方式调用它:
performSegue(withIdentifier: "mySegueID", sender: nil)
对于旧版本:
performSegueWithIdentifier("mySegueID", sender: nil)
你还可以:
presentViewController(nextViewController, animated: true, completion: nil)
或者如果你在导航控制器中:
self.navigationController?.pushViewController(nextViewController, animated: true)
另一个选择是使用模态segue
步骤1:转到故事板,给视图控制器一个故事板ID。您可以在右侧的标识检查器中找到更改故事板ID的位置。
让我们调用故事板ID ModalViewController
第二步:打开'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)
}
}
}
注意,我们要打开的视图控制器也叫做ModalViewController
步骤3:关闭ModalViewController,添加这个
public class ModalViewController {
@IBAction func closeThisViewController(_ sender: Any?) {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
}
Swift 3 -也与SpriteKit一起工作
你可以使用NSNotification。
例子:
1)。在故事板中创建一个segue并将标识符命名为segue
2)。在你要segue的ViewController中创建一个函数。
func goToDifferentView() {
self.performSegue(withIdentifier: "segue", sender: self)
}
3)。在ViewController的ViewDidLoad()中,你从创建观察者开始segue。
NotificationCenter.default.addObserver(self, selector: #selector(goToDifferentView), name: "segue" as NSNotification.Name, object: nil)
更新- - -
上次我使用这个时,我不得不将. addobserver调用更改为下面的代码来消除错误。
NotificationCenter.default.addObserver(self, selector: #selector(goToDifferentView), name: NSNotification.Name(rawValue: "segue"), object: nil)
4)。在你要segue到的ViewController或Scene中,在你想要segue被触发的地方添加Post方法。
NotificationCenter.default.post(name: "segue" as NSNotification.Name, object: nil)
更新- - -
上次我使用它时,我不得不将.post调用更改为以下代码来消除错误。
NotificationCenter.default.post(NSNotification(name: NSNotification.Name(rawValue: "segue"), object: nil) as Notification)