So I have thisUITableView
cell that has 4 UITextField
, and I want to get their values on button click.
This code does not retrieve any values.
@IBAction func printBtnAction(_ sender: Any) {
let cell = self.myTableView.dequeueReusableCell(withIdentifier: "manualAddC1") as! AddFriendC1Cell
let alias = cell.aliasTextField.text!
let primaryPhone = cell.primaryPhoneTextField.text!
let secondaryPhone = cell.seondaryPhoneTextField.text!
let email = cell.emailAddressTextField.text!
print("Alias: \(alias), Phone: \(primaryPhone), Phone2: \(secondaryPhone), Email: \(email)")
}
This is the screenshot of the TableView
I finally figured it out with this simple solution.
@IBAction func saveBtnAction(_ sender: Any) {
let index = IndexPath(row: 0, section: 0)
let cell: AddFriendC1Cell = self.myTableView.cellForRow(at: index) as! AddFriendC1Cell
self.alias = cell.aliasTextField.text!
self.primaryPhone = cell.primaryPhoneTextField.text!
self.secondaryPhone = cell.seondaryPhoneTextField.text!
self.email = cell.emailAddressTextField.text!
print("Alias: \(self.alias), Phone: \(self.primaryPhone), Phone2: \(self.secondaryPhone), Email: \(self.email)")
}
OK. You are dequeueing a tableViewCell when you press on a button.
let cell = self.myTableView.dequeueReusableCell(withIdentifier: "manualAddC1") as! AddFriendC1Cell
I believe that you want to get a reference to an existing tableViewCell like this:
if let cell = tableView.cellForRow(at: indexPath) as? AddFriendC1Cell {
// do what you need with cell
}
Even though this would work, I wouldn't suggest this approach. What if user is using a smaller-screen phone like iPhone 4 and some cells are not visible on the screen? I think that in that case tableView.cellForRow
would return nil
for non-visible cell.
I would suggest implementing textField:shouldChange
in each cell with text field with a delegate to the tableView's viewController. When text is changed in the cell, delegate should propagate the change to the viewController which would save the value in an instance variable.
Then, when you press on the button, you would simply take values from instance variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With