rutheferd
rutheferd

Reputation: 109

Getting Ordered TextField Data From Dynamically Created Cells in Swift (3.1) Table View

I am trying to figure out how to get textfield data from cells in a tableview in an ordered fashion. So far I am able to type into each textfield a retrieve the type data. To do so in the correct order though the user must edit the first cell...last cell, any other way and the data isn't in the correct order.

For Example:

I have the program create 5 cells with a textfield,

the way I currently have it my dataArray would look identical to this one, because it is being stored based on when it is typed in and not the order of the cells. I would like to type the above example, but my data come out like this:

Here is my textfield editing code:

@IBAction func TitleEditBegin(_ sender: UITextField) {
}

@IBAction func TitleEditEnd(_ sender: UITextField) {
    print(sender.tag) // Debug
    titleArray.append(sender.text!)
}

I know for the time being that any other changes will be appended to the titleArray, but I want to solve the ordering issue first.

Thanks!

EDIT: I forgot to add in how I am creating the cells, the code is below:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = TitleSessionTableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath) as! TitleSessionCell

    cell.SessionTitleLabel.text = "Title"
    // cell.SessionTitleField.text = "Default"
    cell.SessionTitleField.tag = indexPath.row
    cell.SessionTitleField.delegate = self
    print(indexPath.row) // Debug

    return cell

}

EDIT 2: Adding where I define the text fields.

import Foundation
import UIKit

class TitleSessionCell: UITableViewCell{

@IBOutlet weak var SessionTitleField: UITextField!
@IBOutlet weak var SessionTitleLabel: UILabel!


override func awakeFromNib() {
    super.awakeFromNib()
}


}

Upvotes: 0

Views: 703

Answers (1)

Sethmr
Sethmr

Reputation: 3084

The easiest way would be to use a dictionary I believe. I would assign all of the textFields a different tag. So for textField1 you would say textField1.tag = 1. I don't see the creation of your text fields, so it is hard to show the best way of adding that in, but then after handling that, I would create the dictionary as a class variable.

var textFieldDictionary: [Int: String] = [:]

and then add in the text to it like so:

if sender.text != nil && sender.text != "" {
    textFieldDictionary[sender.tag] = sender.text
}

then when you want to retrieve the information, do something like this:

for i in 0..<biggestTextFieldNumber {
    if let text = textFieldDictionary[i] {
        //do something with text
        print(text)
    }
}

or you could just grab the specific number values out whenever you needed them by using:

textFieldDictionary[numberYouWant]

I hope this helps!

Upvotes: 0

Related Questions