syedfa
syedfa

Reputation: 2809

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. 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 {
    //...
    //}
...
}

Does anyone have any ideas or suggestions?

Upvotes: 0

Views: 265

Answers (2)

Saurabh Prajapati
Saurabh Prajapati

Reputation: 2380

You can try below code. i have tried it in Objective C

NSIndexPath *indexPath = [self.tableview indexPathForRowAtPoint:textField.superview.superview.center];

CustomTableViewCell *cell = [self.tableview cellForRowAtIndexPath:indexPath];
//cell.txt1 is your textfield Object
if(textField == cell.txt1)
{

}

You can convert it in swift.

Upvotes: 0

Lie-An
Lie-An

Reputation: 2563

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:

textField.someId

Upvotes: 2

Related Questions