Jules
Jules

Reputation: 7766

Programatically calling resignFirstResponder on a UITextField without a storyboard

I have a custom UITableViewCell with a UITextField, which has variable in the custom class. I'm not using a storyboard so I don't have an outlet; I'm doing this programmatically.

I'm using textFieldDidEndEditing in my UIViewController to acquire the value a user provides.

    public func textFieldDidEndEditing(_ textField: UITextField)
    {
        print("textvalue=\(textField.text!)")
    }

However, if a navigation bar button is tapped textFieldDidEndEditing is not called. I know normally if I had an outlet and a textfield variable on my UIViewController I could use resignFirstResponder which would probably cause textFieldDidEndEditing to be called, but as I say I'm not using an outlet / storyboard.

I don't have have this variable on my UIViewController for the textfield so I don't have anything to call resignFirstResponder on.

I guess I could call resignFirstResponder in my custom UITableViewCell but I don't have access to my my model.

Upvotes: 2

Views: 409

Answers (1)

Rishil Patel
Rishil Patel

Reputation: 1995

It could be possible by either identify your text field using identifier such as tags and accessibility from UITableViewDelegate then use can use,

Set the delegate when create cell in

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    cell.txtField.delegate = self

  }

  // then it will be called UITextFieldDelegate

  public func textFieldDidEndEditing(_ textField: UITextField)
  {

  }

Or you can use as per hierarchy of subviews:

self.view.endEditing(true)

Upvotes: 4

Related Questions