Michael Williams
Michael Williams

Reputation: 1412

Appending Custom Cell Label and TextField text to Array of Dictionary

I have a custom tableView cell with a UILabel and a UITextField. I would like to append the data from the textField with label to an array of dictionaries ([label:textfield]). I can get the textField data using textFieldDidEndEditing but I am not sure how to get the cell label for that same textfield. I would think I would need access to that cell's indexPath. I tried sending a notification to DidSelectRow but that seemed too complicated.

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: expenseCell, for: indexPath) as! LineItemTableViewCell
        let sectionsArray = expenses[sections[indexPath.section]]
        let expenseItem = sectionsArray?[indexPath.row]
        cell.budgetLineItemView.label.text = expenseItem!
        cell.budgetLineItemView.lineItemTextField.delegate = self

        return cell
    }

    //MARK: UITextField Delegate

    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.layer.borderColor = UIColor.blue.cgColor
        textField.keyboardType = .decimalPad
        textField.becomeFirstResponder()
    }


    func textFieldDidEndEditing(_ textField: UITextField) {
        //get textfield text after editing here
    }

This is my dictionary:

 var expenses:[String:[[String:Double]]] = ["Housing":[["Rent/Mortgage":0.0],
["Gas":0.0],["Water/Power":0.0],["Cable/Internet":0.0],["Garbage":0.0],["Property 
Tax":0.0],["Homeowners/Renters Insurance":0.0]],"Transportation":[["Car 
Payment":0.0],["Car Insurance":0.0],["Roadside Insurance":0.0]],"Other Expenses":
[["Health Insurance":0.0],["Life Insurance":0.0],["Disability Insurance":0.0],
["Student Loans":0.0],["Cell Phone":0.0],["Other":0.0]]]

Upvotes: 0

Views: 847

Answers (1)

Syed Ali Salman
Syed Ali Salman

Reputation: 2915

Can you do something like this?

why not setting up tag to each label and textFiled like follow in your cellForRowAtIndexPath

textField.tag = indexPath.row

and in the delegate textFieldDidBeganEditing or where necessary use the tag to get cell and then the label as below

let indexpath = NSIndexPath(forRow: textField.tag, inSection: 0)
let currentCell = tblTest.cellForRowAtIndexPath(indexpath) as! youCellClass

then using currentCell you may access it's label

Upvotes: 1

Related Questions