How do you share data between view controllers and other objects in Swift?

后端 未结 8 1003
长情又很酷
长情又很酷 2020-11-22 02:15

Say I have multiple view controllers in my Swift app and I want to be able to pass data between them. If I\'m several levels down in a view controller stack, how do I pass d

相关标签:
8条回答
  • 2020-11-22 03:12

    SWIFT 3:

    If you have a storyboard with identified segues use:

    func prepare(for segue: UIStoryboardSegue, sender: Any?)
    

    Although if you do everything programmatically including navigation between different UIViewControllers then use the method:

    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool)
    

    Note: to use the second way you need to make your UINavigationController, you are pushing UIViewControllers on, a delegate and it needs to conform to the protocol UINavigationControllerDelegate:

       class MyNavigationController: UINavigationController, UINavigationControllerDelegate {
    
        override func viewDidLoad() {
            self.delegate = self
        }
    
        func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
    
         // do what ever you need before going to the next UIViewController or back
         //this method will be always called when you are pushing or popping the ViewController
    
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:12

    It depends when you want to get data.

    If you want to get data whenever you want, can use a singleton pattern. The pattern class is active during the app runtime. Here is an example of the singleton pattern.

    class AppSession: NSObject {
    
        static let shared = SessionManager()
        var username = "Duncan"
    }
    
    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
    
            print(AppSession.shared.username)
        }
    }
    

    If you want to get data after any action, can use NotificationCenter.

    extension Notification.Name {
        static let loggedOut = Notification.Name("loggedOut")
    }
    
    @IBAction func logoutAction(_ sender: Any) {
        NotificationCenter.default.post(name: .loggedOut, object: nil)
    }
    
    NotificationCenter.default.addObserver(forName: .loggedOut, object: nil, queue: OperationQueue.main) { (notify) in
        print("User logged out")
    }
    
    0 讨论(0)
提交回复
热议问题