首页 > 解决方案 > 如何将变量从按钮操作函数拉到另一个视图控制器类?

问题描述

我有一段代码

@IBAction func postbutton(_ sender: UIButton) {
   let ref: DatabaseReference = Database.database().reference()
   let postvalue =  ref.child("All Post").childByAutoId()
   let postkeyvalue = postvalue.key!
   postvalue.child("Post Content").setValue(postcontent.text)
   postvalue.child("Post Author").setValue(currentuser)
   var possstkeystring = postkeyvalue
}

我需要访问其他视图控制器文件中的 possstkeystring。

我已经尝试在函数之外声明 possstkeystring。当我这样做时,我的项目总是失败,因为它是空的。

我尝试过使用不起作用的准备功能。

我尝试在类之外声明变量 - 这不起作用。它总是失败,因为字符串为空,并且由于它是 firebase 子字符串,所以它不能为空。

这是我试图将其插入的另一个文件代码块

self.ref.child("All Post").child(possstkeystring).child("Post Author").observe(DataEventType.value, with: { (snapshot) in
     if let item = snapshot.value as? NSDictionary
       { 
          self.authornamereference = item["Post Author"] as! String
       }

请帮忙!谢谢 :)

当我实际输入范围之外的变量或静态变量时,出现此错误

由于未捕获的异常“InvalidPathValidation”而终止应用程序,原因:“(子:)必须是非空字符串且不包含“。” '#' '$' '[' 或 ']''

标签: swiftfirebase

解决方案


您可以通过多种方式进行操作,其中一种方法是使用 NotificationCenter

使用通知中心:

首先,您需要在应用程序的任何位置添加 Notification.Name 的扩展名。喜欢

extension Notification.Name { static let mynotification = Notification.Name("mynotification") }

在您的另一个视图控制器 viewDidLoad 方法中添加

NotificationCenter.default.addObserver(self, selector: #selector(yourMethod), name: NSNotification.Name.mynotification, object: nil)

然后在您的另一个 ViewController 中添加一个方法,该方法将在触发通知时调用

 func yourMethod(){
    //// do something
 }

现在在您的 Click 事件方法中,甚至在应用程序的任何地方,您都可以通过发送通知来调用 viewController 的方法 Like

 NotificationCenter.default.post(name: NSNotification.Name.mynotification, object: nil)
  1. 另一种简单的方法是,如果您从存在单击事件的同一个 viewController 启动另一个 ViewController,那么您必须具有 viewController 的引用。那么你只需要打电话

    vc.yourMethod(params);
    

推荐阅读