I have added textfield in tableview cell and want all textfield values in submitButton
code: how do i get added tableview text in submitButton
class TableCell: UITableViewCell{
@IBOutlet weak var tableLbl: UILabel!
@IBOutlet weak var textFieldData: UITextField!
}
class TableviewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
var selectedRows = [Int]()
var textfieldDataArray = [String]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! TableCell
cell.textFieldData.delegate = self
cell.textFieldData.tag = indexPath.row
cell.textFieldData.addTarget(self, action: #selector(textfieldDidChange(_:)), for: .editingChanged)
cell.tableLbl.text = String(indexPath.row + 1)
return cell
}
@objc func textfieldDidChange(_ textField: UITextField) {
let tag = textField.tag
textfieldDataArray[tag] = textField.text ?? ""
}
@IBAction func submitButton(_ sender: UIButton) {
var selectedTextfieldValues = [String]()
print("Selected Textfield Values: \(selectedTextfieldValues)")
// Use selectedTextfieldValues as needed
}
}
got error at textfieldDataArray[tag] = textField.text ?? ""
Thread 1: Fatal error: Index out of range
I think the better approach is defining a cell data to hold
Stringvalue, it is safer and easier to handle than assigningtagand reusing cell at the same time.It could be:
Then when dequeuing those cells: