我无法访问多个 IndexPath 行文本字段

I can't access multiple IndexPath rows textfields

我是编码的新手,不明白如何正确表达事物以及如何清理我的代码,但这里是。

我有一个视图控制器。在视图控制器中,我有一个视图和一个 table 视图。在视图中,我有一个启用了点击手势的 UIImage 和三个文本字段。在导航栏中,我有一个导航 UIButton。当点击导航 UIButton 时,文本字段中的信息以及图像将发送到我的存储数据库。

在 table 视图中,我有一个原型单元格。在原型单元格中,我有四个文本字段。这些文本字段通过设置 tableviewcell class 来限制。该代码如下所示:

import UIKit
import Firebase

class ConsiderationsCell: UITableViewCell {

@IBOutlet weak var nameTextFieldConsiderations: UITextField!

@IBOutlet weak var feedTextFieldConsiderations: UITextField!

@IBOutlet weak var storyTextFieldConsiderations: UITextField!

@IBOutlet weak var compensationTextFieldConsiderations: UITextField!

override func awakeFromNib() {
super.awakeFromNib()

nameTextFieldConsiderations.placeholder = "Name"
nameTextFieldConsiderations.font = UIFont.systemFont(ofSize: 16)
nameTextFieldConsiderations.translatesAutoresizingMaskIntoConstraints = false
nameTextFieldConsiderations.backgroundColor = UIColor.secondarySystemBackground
nameTextFieldConsiderations.textColor = .label
let nameTFC = nameTextFieldConsiderations.text

feedTextFieldConsiderations.placeholder = "#"
feedTextFieldConsiderations.font = UIFont.systemFont(ofSize: 16)
feedTextFieldConsiderations.translatesAutoresizingMaskIntoConstraints = false
feedTextFieldConsiderations.backgroundColor = UIColor.secondarySystemBackground
feedTextFieldConsiderations.textColor = .label

storyTextFieldConsiderations.placeholder = "#"
storyTextFieldConsiderations.font = UIFont.systemFont(ofSize: 16)
storyTextFieldConsiderations.translatesAutoresizingMaskIntoConstraints = false
storyTextFieldConsiderations.backgroundColor = UIColor.secondarySystemBackground
storyTextFieldConsiderations.textColor = .label

compensationTextFieldConsiderations.placeholder = "$"
compensationTextFieldConsiderations.font = UIFont.systemFont(ofSize: 16)
compensationTextFieldConsiderations.translatesAutoresizingMaskIntoConstraints = false
compensationTextFieldConsiderations.backgroundColor = UIColor.secondarySystemBackground
compensationTextFieldConsiderations.textColor = .label
}



required init?(coder: NSCoder) {
super.init(coder: coder)
 }

}

我现在有一个发送功能,可以将第一行的数据发送到我的 firebase 数据库。该函数的代码如下:

 import UIKit
 import Firebase

class ConsiderationsViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var tableView: UITableView!

var numberOfPeople: [String] = []

var AddPersonCell = "AddPersonCell"

@IBOutlet weak var CompanyImage: UIImageView!

@IBOutlet weak var companyNameTextFieldConsiderations: UITextField!

@IBOutlet weak var companyDescriptionTextFieldConsiderations: UITextField!

@IBOutlet weak var startDateTextFieldConsiderations: UITextField!

@IBOutlet weak var endDateTextFieldConsiderations: UITextField!

let datePickerS = UIDatePicker()
let datePickerE = UIDatePicker()

    var database: Database!
    var storage: Storage!
    var selectedImage: UIImage?
    
    var ref:DatabaseReference?
    var databaseHandle:DatabaseHandle = 0
    
    let dbref = Database.database().reference()
    let uid = Auth.auth().currentUser?.uid
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self
        
        self.companyNameTextFieldConsiderations.delegate = self
        self.companyDescriptionTextFieldConsiderations.delegate = self
        
        // Set the Firebase reference
        ref = Database.database().reference()
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ConsiderationsViewController.handleSelectCompanyImageView))
         CompanyImage.addGestureRecognizer(tapGesture)
         CompanyImage.isUserInteractionEnabled = true

        self.navigationController!.navigationBar.isTranslucent = false
        
        navigationItem.backBarButtonItem = UIBarButtonItem(
        title: "", style: .plain, target: nil, action: nil)
        
        createDatePickerForStart()
        
        createDatePickerForEnd()
        
    }

    @objc func handleSelectCompanyImageView() {

        let pickerController = UIImagePickerController()
        pickerController.delegate = self
        pickerController.allowsEditing = true
        present(pickerController, animated: true, completion: nil)
                    }
    
  @IBAction func AddPersonTapped(_ sender: Any) {
    numberOfPeople.append("#")
    
    DispatchQueue.main.async {
                   self.tableView.reloadData()
                   }
}

   @IBAction func sendButtonTapped(_ sender: Any) {
    
    let companyNameC = companyNameTextFieldConsiderations.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    let companyDescriptionC = companyDescriptionTextFieldConsiderations.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    
    let today = Date()
    let formatter1 = DateFormatter()
    formatter1.dateFormat = "MMM d y"
    print(formatter1.string(from: today))
    let todaysDate = formatter1.string(from: today)
            
    let storageRef = Storage.storage().reference(forURL: "MY STORAGE URL HERE")
    let imageName = companyNameTextFieldConsiderations.text!
    let storageCompanyRef = storageRef.child("Company_Image_Considerations").child("\(todaysDate)").child(imageName)
    let companyDescriptionTextFieldText = companyDescriptionTextFieldConsiderations.text
    let dateToStart = startDateTextFieldConsiderations.text
    let dateToDecide = endDateTextFieldConsiderations.text
    let companyRef = Database.database().reference().child("Considerations").child("\(todaysDate)").child(imageName)
    let index = IndexPath(row: 0,section: 0)
    let cell = tableView.cellForRow(at:index) as! ConsiderationsCell
    let nameTFC = cell.nameTextFieldConsiderations.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    let feedTFC = cell.feedTextFieldConsiderations.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    let storyTFC = cell.storyTextFieldConsiderations.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    let compensationTFC = cell.compensationTextFieldConsiderations.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    
    let values = ["Feed_Quantity": feedTFC, "Story_Quantity": storyTFC, "Compensation": compensationTFC]
    let considerationInfluencerRef = Database.database().reference().child("Considerations").child("\(todaysDate)").child(imageName).child("Users").child("\(nameTFC)")
    
        guard let imageSelected = self.CompanyImage.image else {
            print ("Avatar is nil")
            return
                }
                   
                var dict: Dictionary<String, Any> = [
                    "Company Image": "",
                    "Company Description": companyDescriptionTextFieldText!,
                    "Start Date": dateToStart!,
                    "Decision Date": dateToDecide! ]
    
                   
        guard let imageData = imageSelected.jpegData(compressionQuality: 0.5) else {
            return
                }
    
                let metadata = StorageMetadata()
                metadata.contentType = "image/jpeg"
                storageCompanyRef.putData(imageData, metadata: metadata, completion:
                { (StorageMetadata, error) in
                if (error != nil) {
                return
                    }
                            
                storageCompanyRef.downloadURL { (url, error) in
                if let metadateImage = url?.absoluteString {
                dict["Company Image"] = metadateImage
                   
                companyRef.updateChildValues(dict, withCompletionBlock:  {
                (error, ref) in
                if error == nil {
                print("Done")
                return
                    }
                  }
                )
               }
             }
                            
                                   storageRef.updateMetadata(metadata) { metadata, error in
                                    if error != nil {
                                    //Uh-oh, an error occurred!
                                    } else {
                                    // Updated metadata for 'images/forest.jpg' is returned
                                }
                            }
                        })

    considerationInfluencerRef.updateChildValues(values as [AnyHashable : Any]) { (error, ref) in
    if error != nil {
    print(error ?? "")
    return
                       }
    
self.navigationController?.popViewController(animated: true)
    }
}


func createDatePickerForStart() {
    // center text in field
    startDateTextFieldConsiderations.textAlignment = .center
    
    // toolbar
    let toolbar = UIToolbar()
    toolbar.sizeToFit()
    
    // barbutton
    let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressedStart))
    toolbar.setItems([doneButton], animated: true)
    
    // assign toolbar to textfield
    
    startDateTextFieldConsiderations.inputAccessoryView = toolbar
    
    // assign datePicker to text field
    startDateTextFieldConsiderations.inputView = datePickerS
    
    // date picker mode
    datePickerS.datePickerMode = .date
    
}

func createDatePickerForEnd() {
    // center text in field
    endDateTextFieldConsiderations.textAlignment = .center
    
    // toolbar
    let toolbar = UIToolbar()
    toolbar.sizeToFit()
    
    // barbutton
    let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressedEnd))
    toolbar.setItems([doneButton], animated: true)
    
    // assign toolbar to textfield
    endDateTextFieldConsiderations.inputAccessoryView = toolbar
    
    // assign datePicker to text field
    endDateTextFieldConsiderations.inputView = datePickerE
    
    // date picker mode
    datePickerE.datePickerMode = .dateAndTime
}

@objc func donePressedStart() {
    // formatter
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .none
    
    startDateTextFieldConsiderations.text = formatter.string(from: datePickerS.date)
    self.view.endEditing(true)
}

@objc func donePressedEnd() {
    // formatter
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .medium
    
    endDateTextFieldConsiderations.text = formatter.string(from: datePickerE.date)
    self.view.endEditing(true)
     }

   }
    
   extension ConsiderationsViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
               func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
                   //print("did Finish Picking Media")
                   if let image = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerEditedImage")] as? UIImage{
                       selectedImage = image
                       CompanyImage.image = image
                   }
                   dismiss(animated: true, completion: nil)
               }
    }

   extension ConsiderationsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return numberOfPeople.count
   }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: AddPersonCell, for: indexPath) as! ConsiderationsCell
    
    return cell
   }

}

我可以使用此函数获取发送的第一行文本字段,它在我的数据库中看起来如下所示:

我可以发送第二行,但我必须将索引路径更改为:

let index = IndexPath(row: 1,section: 0)

我想让每一行在每个用户节点下添加名称文本字段名称。我还希望每行中的提要、故事和补偿文本字段位于它们对应的每个名称文本字段节点下。

如果有更好的方法来做到这一点,我已经好多年了。在过去的两周里,我一直在尝试这样做。

(将来我需要帮助我的数据库中特定用户对应的名称文本字段,并能够向他们显示公司信息以及他们的特定节点信息)

请帮忙!!!

这有帮助吗?

    for index in 0..<numberOfPeople {
        let indexPath = IndexPath(item: index, section: 0)
        let cell = tableView.cellForRow(at: indexPath) as? ConsiderationsCell
        let nameTFC = cell?. nameTextFieldConsiderations.text!
        //Get all fields
        // Call FB method
    }

为了正确 indexPath.row,我需要将标签设置为其对应的文本字段。这是我最终使用的代码:

extension ConsiderationsTestViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    return ConsiderationsTestViewController.people.count
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 72
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: AddPersonCell, for: indexPath) as! ConsiderationsCell
    
    let numberOfPeopleCells = ConsiderationsTestViewController.people[indexPath.row]
    
    
    cell.nameLabelC.text = numberOfPeopleCells.Name
    cell.feedLabelC.text = numberOfPeopleCells.PostNumber
    cell.storyLabelC.text = numberOfPeopleCells.StoryNumber
    cell.compensationLabelC.text = numberOfPeopleCells.Compensation
    cell.userImage.loadImageUsingCacheWithUrlString(urlString: numberOfPeopleCells.ProfileImageUrl!)
    
    cell.userImage.layer.cornerRadius = 25
    
    cell.nameLabelC.numberOfLines = 0
    
    return cell
}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == .delete) {
        
        ConsiderationsTestViewController.people.remove(at: indexPath.row)
        // handle delete (by removing the data from your array and updating the tableview)
        tableView.deleteRows(at: [indexPath], with: .fade)
    }
}

}