swift - 如何将变量从按钮操作函数拉到另一个视图控制器类?
问题描述
我有一段代码
@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”而终止应用程序,原因:“(子:)必须是非空字符串且不包含“。” '#' '$' '[' 或 ']''
解决方案
您可以通过多种方式进行操作,其中一种方法是使用 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)
另一种简单的方法是,如果您从存在单击事件的同一个 viewController 启动另一个 ViewController,那么您必须具有 viewController 的引用。那么你只需要打电话
vc.yourMethod(params);
推荐阅读
- listview - 使用 StreamBuilder 和从 Firebase Firestore 数据库查询时,ListView 不会更新/获取数据
- c# - 在 IIS 上发布后如何查看异常的详细信息
- flutter - Flutter 中的提供程序出现错误“在此 X 小部件上方找不到正确的提供程序”
- python - 如果 JSON 中不存在列,如何将值插入为空?
- swift - SwiftUI如何防止视图重新加载整个身体
- c++ - C++ 命名空间中的函数未在 Visual Studio 2019 中编译
- java - JavaFX 未启动
- git - 返回“初始提交”会产生不完整的文件
- javascript - 为什么我的编辑页面在 Laravel 中不起作用?我使用了 vue.js
- google-cloud-platform - 为什么 Bigquery 的日内表中有随机日期数据?