[英]Passing a variable to another view controller and showing data in a tableview
我在我的 iOS 應用中使用 Firebase 和 Swift。 我有 2 個帶有 tableviews 的視圖控制器。 我想在單擊單元格的附件按鈕時將數據從 tableview 單元格(即 postkey)傳遞到下一個視圖控制器。 我想從 url https://xxxx.firebaseio.com/users/(uid)/posts/(postkey)/offers 中檢索數據,並在第二個 tableview 中顯示與 postKey 對應的所有優惠。 這是第一個視圖控制器的代碼:
func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath){
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as! FavorCell
postKey = currentCell.postKey.text
performSegueWithIdentifier("seguetoAccept", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let viewControllerAccept = segue.destinationViewController as! AcceptVC
viewControllerAccept.postKey = postKey
//passing the postKey to AcceptVC's postKey
}
這是第二個視圖控制器的代碼:
override func viewDidLoad() {
super.viewDidLoad()
bidTableView.delegate = self
bidTableView.dataSource = self
let bidCell = Firebase(url:"https://xxxx.firebaseio.com/users/\(uid)/posts/\(postkey)/offers")
bidCell.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.value)
self.favors = []
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot]{
for snap in snapshots {
print("SNAP: \(snap)")
if let postdic = snap.value as? Dictionary <String, AnyObject>{
let key = snap.key
let offer = Offer(bidKey: key, dictionary: postdic)
self.favors.append(offer)
}
}
}
self.bidTableView.reloadData()
})
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return favors.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let favor = favors[indexPath.row]
if let cell = tableView.dequeueReusableCellWithIdentifier("acceptCell") as? AcceptCell {
var img: UIImage?
cell.configureCell(favor)
return cell
} else {
return AcceptCell()
}
}
第二個 tableview 沒有顯示任何數據。 就從 Firebase 檢索數據而言,希望檢查我的代碼中是否存在錯誤。
您需要按如下方式更正您的代碼。
func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath){
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as! FavorCell
postKey = currentCell.postKey.text
performSegueWithIdentifier("seguetoAccept", sender: postKey)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "seguetoAccept" {
let viewControllerAccept = segue.destinationViewController as! AcceptVC
let postKey = sender as? String
viewControllerAccept.postKey = postKey
}
//passing the postKey to AcceptVC's postKey
}
您還需要將 postKey 變量添加到第二個視圖控制器中
var postKey:String?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.