CY.L
CY.L

Reputation: 35

Handling delegate of UItextfield in UItableView

I have a UItextfield in one of the cell in my UItable, I want few steps can be execute after return from the text field:

  1. Clear out emptyspace at beginning and the end(Trim whitespace)
  2. resign first responder (hide the keyboard)
  3. set the cell isselected
  4. append the text content of the field into a [String]

But so far I only can able to execute some of it, cause the point 3 is in TableViewCell class but point 4 is in TableViewController. I have tried to make the UItextField outlet to both class, but it's not working Text_NewName.delegate = self Or should I access the [String] in the UITableViewCell class? but when I tried to make it as subclass, swift prompt error 'Multiple inheritance from classes'

I do believe there must have some gap in my knowledge, makes these function to hard, please let me know if have a easier way to make it work too.

Here is the code:

class Namelist_ADDName_TVCell: UITableViewCell, UITextFieldDelegate {
override func awakeFromNib() {
    super.awakeFromNib()
    Text_NewName.delegate = self
}
@IBOutlet weak var Text_NewName: UITextField!

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    textField.text = textField.text?.trimmingCharacters(in: .whitespaces)
    textField.resignFirstResponder()

    if textField.text != "" {
        self.isSelected = true
        return true
    } else {
        self.isSelected = false
        return false
    }

}

Another swift file:

class PickNameTVC: UITableViewController, UITextFieldDelegate {

var selectedlist : [String]?

func textFieldShouldReturn(_ theTextfield: UITextField) -> Bool {

    if theTextfield.text != "" {
        selectedlist?.append(theTextfield.text!)
    }
    return true
}
}

Upvotes: 2

Views: 4735

Answers (1)

Fernando Romiti
Fernando Romiti

Reputation: 175

Manage everything on the PickNameTVC.

Set the delegate when you create the cell on override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell method set your delegate like cell.textField.delegate = self (where cell is your dequeued cell in that method).

Upvotes: 6

Related Questions