在Swift中将通知从一个Viewcontroller推送到另一个Viewcontroller?

时间:2018-04-27 13:17:25

标签: ios swift xcode

我想将通知从一个(第一个)ViewController推送到(第二个)另一个ViewController,而此通知采用第一个ViewController的函数并打印函数的结果。我怎样才能做到这一点?请帮助,我搜索了所有的互联网没有结果。

2 个答案:

答案 0 :(得分:0)

试试这个

发布通知:(第一个ViewController)

NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil, userInfo: ["key":"value"])

获取通知:(第二个ViewController)

NotificationCenter.default.addObserver(self, selector: #selector(self.ReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)

处理收到的通知的方法:

@objc func ReceivedNotification(notification: Notification){

    //Take Action on Notification

}

答案 1 :(得分:0)

您可以轻松地使用协议在控制器之间传递数据,与观察者相同

第1步创建协议存根

 /// Protcol 
    @objc protocol showViews : class {
        /// An optional func inside protocol that will
        /// be used to pass the required Data
        /// For now, I am just passing a Bool Value
        @objc optional func showToggleMenu(needToShow:Bool)
    }

源ViewController - 从中​​传递数据的控制器

/// Source Controller
class mainHomeVC: UIViewController 
{
   /// Create a referencing object for the protocol
   var delegate : showViews?


    /// To pass data just call the delegate and its function
    @IBAction func showToggleMenu(_ sender: UIButton)
    {
        /// Pass Data
        delegate?.showToggleMenu!(needToShow: true)
    }
}

目标控制器需要传递数据的控制器

/// Destination Controller
class homeVC: UIViewController 
{
   /// Create a reference of class from which data is to be fetched
   private lazy var mainHomeVCObjet: mainHomeVC =
    {
        // Instantiate View Controller
        let viewController = self.storyboard?.instantiateViewController(withIdentifier: "mainHomeVC") as! mainHomeVC
        viewController.delegate = self
        // Add View Controller as Child View Controller
        self.addChildViewController(viewController)
        return viewController
    }()
}

//MARK: Protocol Extension
extension homeVC : showViews
{
    //MARK: Show Side Menu ?
    func showToggleMenu(needToShow: Bool)
    {
        if (needToShow)
        {
            print("time to show a toggle Menu")
        }
    }
}