我正在尝试将文本从一个ViewController发送到下一个,我无法在接收端显示任何数据。数据来自表视图,解析数据到常规ViewController。最后一个函数中的idLabel需要在接收端更新。
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableViewProducts: UITableView!
var ref:DatabaseReference?
var databaseHandle: DatabaseHandle?
var postData = [String]()
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference()
databaseHandle = ref?.child("0").observe(.childAdded, with: { (snapshot) in
let post = snapshot.value as? String
if let actualPost = post {
self.postData.append(actualPost)
self.tableViewProducts.reloadData()
}
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(postData)
return postData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = postData[indexPath.row]
cell?.textLabel?.textColor = UIColor.white
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
performSegue(withIdentifier: "showDetails", sender: self)
func prepare(for segue: UIStoryboardSegue, for: Any?){
if segue.destination is ProductViewController
{
let vc = segue.destination as? ProductViewController
vc?.idLabel?.text = postData[indexPath.row]
}
}
}
}
答案 0 :(得分:0)
一种解决方案是从tableView函数中取出 func prepare 并利用representObject var。
假设firstVC正在转向secondVC(SecondViewController类)并且你想传递一个字符串,它看起来像这样:
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
let secondVC = segue.destinationController as! SecondController
secondVC.representedObject = "some string"
}
在你的第二个视图控制器中;
@IBOutlet weak var textField: NSTextField!
override func viewWillAppear() {
self.textField.stringValue = self.representedObject as! String
}
答案 1 :(得分:0)
这里的问题是您在代码中显示视图之前尝试更新UI:
vc?.idLabel.text = postData[indexPath.row]
这里有几个选择,最简单的选择是在secondViewController上创建一个变量
class SecondViewController {
var someText: String!
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
idLabel.text = someText
}
}
或者你可以添加一个委托方法并抛弃prepare(对于segue:)
示例:https://medium.com/ios-os-x-development/pass-data-with-delegation-in-swift-86f6bc5d0894