需要在 Swift 中引用 UITextField 委托方法中的自定义 UITableViewCell,而不使用标签 属性

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

我的 UITableView 中有一个包含多个 UITextField 的自定义 UITableViewCell。我的 ViewController 包含我的 tableView 实现 UITextFieldDelegate。这意味着当用户与 textFields 交互时,UITextField 委托方法被触发。

我的问题是我需要从 UITextField 委托方法内部访问包含在自定义 UITableViewCell 中的文本字段。挑战在于:不幸的是,我无法使用 UITextField 具有的 "tag" 属性。 "tag" 属性 被用于其他用途,不幸的是,在项目的这一点上,我无法重构它。

例如,在下面的委托方法中:

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

有没有人有什么想法或建议?

您可以创建 UITextField 的扩展。像这样:

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)

      }

    }

  }

}

然后您可以访问和比较:

textField.someId

您可以试试下面的代码。我已经在 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)
{

}

可以在swift中转换。