syedfa syedfa - 1 year ago 154
iOS Question

Need reference to custom UITableViewCell inside UITextField delegate method in Swift without using the tag property

I have a custom UITableViewCell in my UITableView that contains multiple UITextFields. My ViewController that contains my tableView implements UITextFieldDelegate. This means that the UITextField delegate methods are triggered when the user is interacting with the textFields. My problem is that I need to access the textFields that are contained inside the custom UITableViewCell from inside the UITextField delegate methods. The challenge is this: unfortunately, I am unable to use the "tag" property that the UITextField has (please don't ask me why). The "tag" property is being used for something else, and at this point in the project I unfortunately can't refactor it.

For example, in the following delegate method:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

//instead of: if textField.tag == someNumber
//I would like to have something like:
//if textField == cell.textFieldA {
//} else if textField == cell.textFieldB {

I hope this makes sense. Does anyone have any ideas or suggestions?

Answer Source

you can create an extension of UITextField. something like this:

extension UITextField {

  private struct AssociatedKeys {

    static var someId = "someId"


  @IBInspectable var someId: String? {

    get {

      return objc_getAssociatedObject(self, &AssociatedKeys.someId) as? String


    set {

      if let newValue = newValue {

        objc_setAssociatedObject(self, &AssociatedKeys.someId, newValue as NSString?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)





Then you can access and compare:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download