In a UIViewController I have a UITableView with 1 Dynamic Prototype cell of class type TextInputTableViewCell
.
In the Content View of the prototype cell I am a
You can try this.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TextInputCell") as! TextInputTableViewCell
cell.textField.isEnabled = placeHolderItems[indexPath.row].editable
cell.textField.placeholder = placeHolderItems[indexPath.row].name
if !self.userInfo.isEmpty{
switch indexPath.row {
case 0:
cell.textField.text = self.userInfo[0].FirstName + " " + self.userInfo[indexPath.row].LastName
case 1:
cell.textField.text = self.userInfo[0].PhoneNumber
case 2: cell.textField.text = self.userInfo[0].EmailAddress
case 3: cell.textField.text = self.userInfo[0].FlatNumber
case 4: cell.textField.text = self.userInfo[0].StreetAddress
case 5: cell.textField.text = self.userInfo[0].PostCode
default:
break
}
}
// Add tag to cell textField as cell current index
cell.textField.tag = indexPath.row
//Observer changes as user edits
cell.txtField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
return cell
}
//MARK: - TextField Delegate
func textFieldDidChange(textfield: UITextField) {
print("TextField \(String(describing: textfield.text)) Tag : \(textfield.tag)")
switch textfield.tag {
case 0:
let Name = textfield.text // or store where ever you want in sepearte array or update in userInfo
case 1:
let PhoneNumber = textfield.text
case 2:
let EmailAddress = textfield.text
case 3:
let FlatNumber = textfield.text
case 4:
let StreetAddress = textfield.text
case 5:
let PostCode = textfield.text
default:
break
}
}
// Don't forget to add UITextFieldDelegate
The usual problem to be solved is: The user has a edited a text field in a table view cell, and now we want to update the data model accordingly. But which cell contains this text field?
The notion "which" really means: what is the index path represented by the containing cell? If we knew that, we could easily update the model, because if our table view data source is correctly designed, we already know how to access the model by means of the index path.
So what I do is simply walk up the view hierarchy from the text field to the cell, and then ask the table view what index path this cell represents. This is a commonly used pattern in my apps:
func textFieldDidEndEditing(_ textField: UITextField) {
var v : UIView = textField
repeat { v = v.superview! } while !(v is UITableViewCell)
let cell = v as! MyCell // or UITableViewCell or whatever
let ip = self.tableView.indexPath(for:cell)!
// and now we have the index path! update the model
}