我如何从已经创建的单元格的某个人的点击的火力点上取下钥匙
问题描述:
如何从已经创建的单元格(我使用TableView)的Firebase中取得某人点击的钥匙,并将其创建为本地变量?我想知道这个,所以我可以将密钥传送到下一个视图,这样我就可以创建一个通用故事板,但文本字段会随密钥而变化。这也意味着我想在一个视图控制器中设置数据,然后将它发送给另一个,如果我正在使用相同的数据库(我),我需要它在第二个视图控制器上进行编辑。我如何从已经创建的单元格的某个人的点击的火力点上取下钥匙
我已经有这么多(用于火力)
refObjective = Database.database().reference().child("objective");
// refObjective = Database.database().reference().child("toolbars");
// let bodyFire = refObjective.child("-KwSYtZU_EX1vFFeTI4g").child("body")
let bodyFire = refObjective.childByAutoId().child("body")
bodyFire.observeSingleEvent(of: .value, with: { (snapshot) in
let bodyOnFire = snapshot.value as? String
self.text?.text = bodyOnFire
})
第二视图控制器和整个视图第一/ tableview中控制器
//
// WeeklyObjectivesEditorViewController.swift
// Studioso
//
// Created by Charles Porth on 8/29/17.
// Copyright © 2017 Studioso. All rights reserved.
//
import Foundation
import UIKit
import FirebaseCore
import FirebaseDatabase
class WeeklyObjectivesEditorViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var View2: UITabBarItem!
@IBOutlet weak var toolbar1: UITextField!
//defining firebase reference var
var refToolbars: DatabaseReference!
var refToolbars2: DatabaseReference!
let arrayOfIDs: NSMutableArray = [""]
// @IBOutlet weak var label: UILabel!
@IBOutlet weak var tableViewToolbar: UITableView!
//list to store all the artist
var toolbarList = [ToolbarModel]()
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return toolbarList.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
//creating a cell using the custom class
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell
//the artist object
let toolbar: ToolbarModel
//getting the artist of selected position
toolbar = toolbarList[indexPath.row]
//adding values to labels
cell.label.text = toolbar.toolbar1
//returning cell
return cell
}
@IBOutlet weak var scrollView: UIScrollView!
//1 == up
// @IBOutlet weak var toolbar2: UITextField!
// @IBOutlet weak var toolbar3: UITextField!
// @IBOutlet weak var toolbar4: UITextField!
// @IBOutlet weak var toolbar5: UITextField!
// @IBOutlet weak var toolbar6: UITextField!
// @IBOutlet weak var toolbar7: UITextField!
// @IBOutlet weak var toolbar8: UITextField!
// @IBOutlet weak var toolbar9: UITextField!
// @IBOutlet weak var toolbar10: UITextField!
// @IBOutlet weak var toolbar11: UITextField!
// @IBOutlet weak var toolbar12: UITextField!
// @IBOutlet weak var toolbar13: UITextField!
@IBOutlet weak var Remove: UIBarButtonItem!
@IBOutlet weak var add: UIBarButtonItem!
/*
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "WeeklyObjectivesViewController" {
let WeeklyObjectivesViewController = self.storyboard?.instantiateViewController(withIdentifier: "WeeklyObjectivesViewController") as! WeeklyObjectivesViewController
*/
//https://www.raywenderlich.com/139322/firebase-tutorial-getting-started-2
@IBAction func buttonToolbar(_ sender: UIButton) {
addToolbar()
restructureDBKeys()
//reloading the tableview
self.tableViewToolbar.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
// Add this
tableViewToolbar.delegate = self
tableViewToolbar.dataSource = self
// print(self.selectedKey + "this is the key working ------ ___- -----")
//getting a reference to the node artists
refToolbars = Database.database().reference().child("toolbars");
print(selectedKey + "this is the selected key")
dataPassedMedium = selectedKey
let bodyFire = refToolbars.childByAutoId().child("body")
// let arrayOfIDs: NSMutableArray = [""]
//this is how you get it
refToolbars.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.value is NSNull{
//Handle errors
}
else{
self.arrayOfIDs.removeAllObjects()
if let dict = snapshot.value as? NSDictionary{
//dict.allKeys is all the IDs
for ID in dict.allKeys{
self.arrayOfIDs.add(ID as! String) //Will always be a string in Firebase
}
}
}
})
//observing the data changes
refToolbars.observe(DataEventType.value, with: { (snapshot) in
//if the reference have some values
if snapshot.childrenCount > 0 {
//clearing the list
self.toolbarList.removeAll()
//iterating through all the values
for toolbar in snapshot.children.allObjects as! [DataSnapshot] {
//getting values
let toolbarObject = toolbar.value as? [String: AnyObject]
let toolbarId = toolbarObject?["id"]
let toolbarToolbar1 = toolbarObject?["toolbar1"]
let toolbarBody = toolbarObject?["body"]
let toolbarTitle = toolbarObject?["title"]
// let toolbarSelectedKey = toolbarObject?["selectedKey"]
////
// creating artist object with model and fetched values
// //let toolbar = ToolbarModel(toolbar1: "String?")
//creating artist object with model and fetched values
let toolbar = ToolbarModel(id: toolbarId as! String?, toolbar1: toolbarToolbar1 as! String?, title: toolbarTitle as! String?, body: toolbarBody as! String?)
//appending it to list
self.toolbarList.append(toolbar)
}
//reloading the tableview
self.tableViewToolbar.reloadData()
}
})
// scrollView.contentSize = CGSize(width: view.frame.width, height: view.frame.height + 83)
}
func addToolbar(){
//generating a new key inside artists node
//and also getting the generated key
let key = refToolbars.childByAutoId().key
//creating artist with the given values
let toolbar = ["id":key,
"toolbar1": toolbar1.text! as String,
// "toolbar2": toolbar2.text! as String,
// "toolbar3": toolbar3.text! as String,
// "toolbar4": toolbar4.text! as String,
// "toolbar5": toolbar5.text! as String,
// "toolbar6": toolbar6.text! as String,
// "toolbar7": toolbar7.text! as String,
// "toolbar8": toolbar8.text! as String,
// "toolbar9": toolbar9.text! as String,
// "toolbar10": toolbar10.text! as String,
// "toolbar11": toolbar11.text! as String,
// "toolbar12": toolbar12.text! as String,
]
//adding the artist inside the generated unique key
refToolbars.child(key).setValue(toolbar)
// refToolbars.child(key).setValue(toolbar1)
// refToolbars.child(key).setValue(toolbar2)
// refToolbars.child(key).setValue(toolbar3)
// refToolbars.child(key).setValue(toolbar4)
// refToolbars.child(key).setValue(toolbar5)
// refToolbars.child(key).setValue(toolbar6)
// refToolbars.child(key).setValue(toolbar7)
// refToolbars.child(key).setValue(toolbar8)
// refToolbars.child(key).setValue(toolbar9)
// refToolbars.child(key).setValue(toolbar10)
// refToolbars.child(key).setValue(toolbar11)
// refToolbars.child(key).setValue(toolbar12)
//
//displaying message
// labelMessage.text = "toolbar"
//https://www.simplifiedios.net/firebase-realtime-database-tutorial/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject!) {
// let segueName: String = segue.identifier!;
// if (segueName == "addButton") {
// let weeklyObjectivesViewController = segue.destination as! WeeklyObjectivesViewController;
//
//// weeklyObjectivesViewController.stringPassed1 = toolbar1.text
//
// }
// }
//list to store all the artist
// var toolbarList = [ToolbarModel]()
var valueToPass:String! // #1 i added this one first
var selectedKey: String!
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as! ViewControllerTableViewCell
// valueToPass = currentCell.label.text
//the artist object
// let toolbar: ToolbarModel
//getting the artist of selected position
// toolbar = toolbarList[indexPath.row]
let destinationVC = AddNewObjectiveViewController()
destinationVC.transferRow = selectedKey
selectedKey = (arrayOfIDs[indexPath.row] as? String)!
//selectedKey = toolbar.selectedKey
print(selectedKey + "this is the selected [email protected] selected")
print(dataPassedMedium + "this is the dataPassedMedium [email protected] selected")
dataPassedMedium = selectedKey
self.performSegue(withIdentifier: "weeklyadd", sender: self)
}
func restructureDBKeys() {
// let arrayOfIDs: NSMutableArray = [""]
//this is how you get it
refToolbars.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.value is NSNull{
//Handle errors
}
else{
self.arrayOfIDs.removeAllObjects()
if let dict = snapshot.value as? NSDictionary{
//dict.allKeys is all the IDs
for ID in dict.allKeys{
self.arrayOfIDs.add(ID as! String) //Will always be a string in Firebase
}
}
}
})
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// #2 used if let as? UINavigationController
let destinationVC = navigationController?.topViewController as? AddNewObjectiveViewController
// destinationVC?.transferRow = valueToPass
destinationVC?.transferRow = selectedKey
print("data should be transfered")
dataPassedMedium = selectedKey
// let myVC = storyboard?.instantiateViewController(withIdentifier: "AddNewObjectiveViewController") as! AddNewObjectiveViewController
// myVC.transferRow = selectedKey
// navigationController?.pushViewController(myVC, animated: true)
if let navigationController = segue.destination as? UINavigationController {
let destinationVC = navigationController.topViewController as? AddNewObjectiveViewController
// destinationVC?.transferRow = valueToPass
destinationVC?.transferRow = selectedKey
print("data should be transfered")
}
}
// func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// if segue.identifier == "weeklyadd" {
// if let DVC = segue.destination as? AddNewObjectiveViewController{
// DVC.transferRow = selectedKey
// print("data should be transfered")
// } else {
// print("Data NOT Passed! destination vc is not set to firstVC")
// }
// } else { print("Id doesnt match with Storyboard segue Id") }
// }
//
}
var dataPassedMedium: String!
和整个视图第二个控制器上
//
// AddNewObjective.swift
// Studioso
//
// Created by Charles Porth on 9/21/17.
// Copyright © 2017 Studioso. All rights reserved.
//
import Foundation
import QuartzCore
import UIKit
import FirebaseCore
import FirebaseDatabase
class AddNewObjectiveViewController: UIViewController {
@IBOutlet var text : UITextView?
@IBOutlet var textfield : UITextField!
var transferRow = String()
//defining firebase reference var
var refObjective: DatabaseReference!
//var textString: String!
//var textfieldString: String!
//https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/PersistData.html
@IBAction func Save(_ sender: Any) {
// self.updateToolbar(id: <#String#>)
// addObjective()
// bodyReturn.body = self.text?.text
// bodyReturn.title = self.textfield.text
print(transferRow + "String has been tranfered via tranferRow during save")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//not perimantent
self.text?.layer.borderWidth = 1
self.text?.layer.borderColor = UIColor.red.cgColor
refObjective = Database.database().reference().child("toolbar");
//transferRow = WeeklyObjectivesEditorViewController().selectedKey
transferRow = dataPassedMedium
// toolbar.selectedKey = self.transferRow!
// refObjective = Database.database().reference().child("toolbars");
// let bodyFire = refObjective.child("-KwSYtZU_EX1vFFeTI4g").child("body")
print(transferRow + "String has been tranfered via tranferRow")
let delayInSeconds = 4.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {
// // here code perfomed with delay
//
// let bodyFire = self.refObjective.child(self.transferRow).child("body")
// bodyFire.observeSingleEvent(of: .value, with: { (snapshot) in
// let bodyOnFire = snapshot.value as? String
// self.text?.text = bodyOnFire
//
// })
// let titleFire = self.refObjective.child(self.transferRow).child("title")
// titleFire.observeSingleEvent(of: .value, with: { (snapshot) in
// let titleOnFire = snapshot.value as? String
// self.textfield.text = titleOnFire
//
//
// })
}
}
func addObjective(){
//generating a new key inside artists node
//and also getting the generated key
//let key = refObjective.childByAutoId().key
// let key = refObjective.child("-KwSYtZU_EX1vFFeTI4g").key
//creating artist with the given values
let objective = ["id": self.transferRow,
"body": self.text?.text! as! String,
"title": self.textfield.text! as String
] as [String : Any]
//adding the artist inside the generated unique key
self.self.refObjective.child(self.transferRow).setValue(objective)
//displaying message
}
// func updateToolbar(id:String){
// //creating artist with the new given values
// let objective = ["id":id,
// "body": text?.text! as! String,
// "title": textfield.text! as! String,
// ]
//
// //updating the artist using the key of the artist
// refObjective.child(id).setValue(objective)
//
// }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答
要收集在tableView
中使用的密钥,您可以使用dictionary
或array
- 您的偏好。
//This is the key that is desired.
let bodyFire = refObjective.childByAutoId().child("body")
在didSelectRowAt
会当您选择键:
let selectedKey = arrayOfIDs[indexPath.row] as? String
//
// WeeklyObjectivesEditorViewController.swift
// Studioso
//
// Created by Charles Porth on 8/29/17.
// Copyright © 2017 Studioso. All rights reserved.
//
import Foundation
import UIKit
import FirebaseCore
import FirebaseDatabase
class WeeklyObjectivesEditorView2ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var toolbar1: UITextField!
@IBOutlet weak var View1: UITabBarItem!
//defining firebase reference var
var refToolbars2: DatabaseReference!
let arrayOfIDs: NSMutableArray = [""]
// @IBOutlet weak var label: UILabel!
@IBOutlet weak var tableViewToolbar: UITableView!
//list to store all the artist
var toolbarList = [View2ToolbarModel]()
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return toolbarList.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
//creating a cell using the custom class
let cell1 = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! ViewControllerTableViewCell2
//the artist object
let toolbar: View2ToolbarModel
//getting the artist of selected position
toolbar = toolbarList[indexPath.row]
//adding values to labels
cell1.label.text = toolbar.toolbar1
//returning cell
return cell1
}
@IBOutlet weak var scrollView: UIScrollView!
//1 == up
// @IBOutlet weak var toolbar2: UITextField!
// @IBOutlet weak var toolbar3: UITextField!
// @IBOutlet weak var toolbar4: UITextField!
// @IBOutlet weak var toolbar5: UITextField!
// @IBOutlet weak var toolbar6: UITextField!
// @IBOutlet weak var toolbar7: UITextField!
// @IBOutlet weak var toolbar8: UITextField!
// @IBOutlet weak var toolbar9: UITextField!
// @IBOutlet weak var toolbar10: UITextField!
// @IBOutlet weak var toolbar11: UITextField!
// @IBOutlet weak var toolbar12: UITextField!
// @IBOutlet weak var toolbar13: UITextField!
@IBOutlet weak var Remove: UIBarButtonItem!
@IBOutlet weak var add: UIBarButtonItem!
/*
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "WeeklyObjectivesViewController" {
let WeeklyObjectivesViewController = self.storyboard?.instantiateViewController(withIdentifier: "WeeklyObjectivesViewController") as! WeeklyObjectivesViewController
*/
//https://www.raywenderlich.com/139322/firebase-tutorial-getting-started-2
@IBAction func buttonToolbar(_ sender: UIButton) {
addToolbar()
//reloading the tableview
self.tableViewToolbar.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
refObjective(of: .value, with: { (snapshot) in
if snapshot.value is NSNull{
//Handle errors
}
else{
arrayOfIDs.removeAllObjects()
if let dict = snapshot.value as? NSDictionary{
//dict.allKeys is all the IDs
for ID in dict.allKeys{
arrayOfIDs.add(ID as! String) //Will always be a string in Firebase
self.tableView.reloadData()
}
}
}
})
// Add this
tableViewToolbar.delegate = self
tableViewToolbar.dataSource = self
//getting a reference to the node artists
refToolbars2 = Database.database().reference().child("toolbarsView2");
//observing the data changes
refToolbars2.observe(DataEventType.value, with: { (snapshot) in
//if the reference have some values
if snapshot.childrenCount > 0 {
//clearing the list
self.toolbarList.removeAll()
//iterating through all the values
for toolbar in snapshot.children.allObjects as! [DataSnapshot] {
//getting values
let toolbarObject = toolbar.value as? [String: AnyObject]
let toolbarId = toolbarObject?["id"]
let toolbarToolbar1 = toolbarObject?["toolbar1"]
//creating artist object with model and fetched values
//let toolbar = ToolbarModel(toolbar1: "String?")
//creating artist object with model and fetched values
let toolbar = View2ToolbarModel(id: toolbarId as! String?, toolbar1: toolbarToolbar1 as! String?)
//appending it to list
self.toolbarList.append(toolbar)
}
//reloading the tableview
self.tableViewToolbar.reloadData()
}
})
// scrollView.contentSize = CGSize(width: view.frame.width, height: view.frame.height + 83)
}
func addToolbar(){
//generating a new key inside artists node
//and also getting the generated key
let key = refToolbars2.childByAutoId().key
//creating artist with the given values
let toolbar = ["id":key,
"toolbar1": toolbar1.text! as String,
// "toolbar2": toolbar2.text! as String,
// "toolbar3": toolbar3.text! as String,
// "toolbar4": toolbar4.text! as String,
// "toolbar5": toolbar5.text! as String,
// "toolbar6": toolbar6.text! as String,
// "toolbar7": toolbar7.text! as String,
// "toolbar8": toolbar8.text! as String,
// "toolbar9": toolbar9.text! as String,
// "toolbar10": toolbar10.text! as String,
// "toolbar11": toolbar11.text! as String,
// "toolbar12": toolbar12.text! as String,
]
//adding the artist inside the generated unique key
refToolbars2.child(key).setValue(toolbar)
// refToolbars.child(key).setValue(toolbar1)
// refToolbars.child(key).setValue(toolbar2)
// refToolbars.child(key).setValue(toolbar3)
// refToolbars.child(key).setValue(toolbar4)
// refToolbars.child(key).setValue(toolbar5)
// refToolbars.child(key).setValue(toolbar6)
// refToolbars.child(key).setValue(toolbar7)
// refToolbars.child(key).setValue(toolbar8)
// refToolbars.child(key).setValue(toolbar9)
// refToolbars.child(key).setValue(toolbar10)
// refToolbars.child(key).setValue(toolbar11)
// refToolbars.child(key).setValue(toolbar12)
//
//displaying message
// labelMessage.text = "toolbar"
//https://www.simplifiedios.net/firebase-realtime-database-tutorial/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject!) {
// let segueName: String = segue.identifier!;
// if (segueName == "addButton") {
// let weeklyObjectivesViewController = segue.destination as! WeeklyObjectivesViewController;
//
//// weeklyObjectivesViewController.stringPassed1 = toolbar1.text
//
// }
// }
//
}
//
// AddNewObjective.swift
// Studioso
//
// Created by Charles Porth on 9/21/17.
// Copyright © 2017 Studioso. All rights reserved.
//
import Foundation
import QuartzCore
import UIKit
import FirebaseCore
import FirebaseDatabase
class AddNewObjectiveViewController: UIViewController {
@IBOutlet var text : UITextView?
@IBOutlet var textfield : UITextField!
var selectedKey = ""
var transferRow: String = ""
//defining firebase reference var
var refObjective: DatabaseReference!
//var textString: String!
//var textfieldString: String!
//https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/PersistData.html
@IBAction func Save(_ sender: Any) {
// self.updateToolbar(id: <#String#>)
addObjective()
// bodyReturn.body = self.text?.text
// bodyReturn.title = self.textfield.text
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//not perimantent
self.text?.layer.borderWidth = 1
self.text?.layer.borderColor = UIColor.red.cgColor
print(selectedKey)
refObjective = Database.database().reference().child("toolbar");
// toolbar.selectedKey = self.transferRow!
// refObjective = Database.database().reference().child("toolbars");
// let bodyFire = refObjective.child("-KwSYtZU_EX1vFFeTI4g").child("body")
print(self.transferRow)
// let bodyFire = self.refObjective.child(transferRow).child("body")
// bodyFire.observeSingleEvent(of: .value, with: { (snapshot) in
// let bodyOnFire = snapshot.value as? String
// self.text?.text = bodyOnFire
//
////
// let titleFire = self.refObjective.child("id").child("title")
// titleFire.observeSingleEvent(of: .value, with: { (snapshot) in
// let titleOnFire = snapshot.value as? String
// self.textfield.text = titleOnFire
//
// })
//This is the key that is desired.
// self.transferRow = WeeklyObjectivesEditorViewController.toolbarList[indexPath.row]
//
}
func addObjective(){
//generating a new key inside artists node
//and also getting the generated key
//let key = refObjective.childByAutoId().key
// let key = refObjective.child("-KwSYtZU_EX1vFFeTI4g").key
//creating artist with the given values
let objective = ["id": self.transferRow,
"body": text?.text! as! String,
"title": textfield.text! as String
] as [String : Any]
//adding the artist inside the generated unique key
refObjective.child(self.transferRow).setValue(objective)
//displaying message
}
// func updateToolbar(id:String){
// //creating artist with the new given values
// let objective = ["id":id,
// "body": text?.text! as! String,
// "title": textfield.text! as! String,
// ]
//
// //updating the artist using the key of the artist
// refObjective.child(id).setValue(objective)
//
// }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
+0
评论不适用于扩展讨论;这个对话已经[转移到聊天](http://chat.stackoverflow.com/rooms/157091/discussion-on-answer-by-torewin-how-would-i-pull-the-key-from-firebase-的-AN-ALR)。 – Andy
你基本上要获得'childByAutoId()'? – Torewin