我目前在单元格中有一张图片,三张UILabel和一个TextView,并希望在单独的视图控制器中使用该数据。视图控制器当前通过push segue连接到单元,我该怎么做呢?
我有这个,但它不起作用:
let uid = FIRAuth.auth()?.currentUser?.uid
FIRDatabase.database().reference().child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
self.userLabel.text = dictionary["username"] as? String
}
})
答案 0 :(得分:0)
将一个类型为Dictionary的存储变量添加到源VC和目标VC:var userdata:Dictionary!或者你可以初始化一个空字典让userdata = String:Any
然后,在将快照转换为字典后,将源VC用户数据设置为字典数据并执行segue
if let dictionary = snapshot.value as? [String: AnyObject] {
self.userLabel.text = dictionary["username"] as? String
self.userdata = dictionary
self.performSegue(withIdentifier: "<segueIDHere>", sender: self)
}
然后在源VC中实现VC准备segue方法传递数据:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "<segueIDHere>" {
let destinationVC = segue.destination as! <ClassNameofVCHere>
destinationVC.userdata = self.userdata
}
}
答案 1 :(得分:0)
我实际上能找到一种方法来做到这一点。实际上很简单
prepareForSegue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetails" {
if let indexPath = self.postsTableView.indexPathForSelectedRow {
let post = posts[indexPath.row] as! [String: AnyObject]
let postDetails = post["postID"] as? String
let controller = segue.destination as! PostDetailsViewController
controller.postDetails = postDetails
}
}
}
PostDetailsViewController
var postDetails: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
FIRDatabase.database().reference().child("posts").child(postDetails!).observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
self.idLabel.text = dictionary["postID"] as? String
}
})
}