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

后端 未结 8 1005
长情又很酷
长情又很酷 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
    
        }
    }
    

提交回复
热议问题