2

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
}
}
KSR
  • 1,699
  • 15
  • 22
CY.L
  • 35
  • 1
  • 5
  • You need to pick whether to have the UITableViewController subclass or the UITableViewCell subclass be the delegate of the text field. In this scenario, it makes sense for your UITableViewController be the delegate to the text field so it can easily accomplish all four of your tasks. – Josh Hamet Dec 10 '16 at 03:21

1 Answers1

6

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).

  • I did tried to set the text field delegate in viewdidload in picknameTVC, will try to set it in cellforrow tonight. What is the different between them except the running time different?? – CY.L Dec 12 '16 at 04:19
  • Thanks for you and @josh Hamet advises, I figure it out how to make it work after focus on only delegate to Table View Controller. let index = IndexPath(row: (namelist?.count)!, section: 0) self.tableView.selectRow(at: index, animated: true, scrollPosition: .bottom) – CY.L Dec 13 '16 at 03:51