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

Posted

技术标签:

【中文标题】需要在 Swift 中的 UITextField 委托方法中引用自定义 UITableViewCell 而不使用 tag 属性【英文标题】:Need reference to custom UITableViewCell inside UITextField delegate method in Swift without using the tag property 【发布时间】:2016-07-01 03:49:40 【问题描述】:

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

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

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

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

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

【问题讨论】:

我建议您的单元子类应该实现文本字段委托,并通过另一个委托协议将相关事件传递回您的视图控制器 这发生在我身上(即让我的单元子类实现 UITextFieldDelegate),但我不确定如何将单元子类中的事件与包含 UITableView 的 UIViewController 链接起来。 让视图控制器实现您的新协议(您定义的),并将自己设置为cellForRowAtIndexPath中的单元格委托 【参考方案1】:

您可以创建 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

【讨论】:

非常感谢您的及时答复。您能否详细说明您在做什么的解决方案? 我想我明白了。您正在做的是将另一个属性附加到 UITextField,其功能与“标记”属性相同,对吗? 是的,正确。你只需要调整你需要使用的变量的类型。【参考方案2】:

你可以试试下面的代码。我已经在 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 中的 UITextField 委托方法中引用自定义 UITableViewCell 而不使用 tag 属性的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Swift 中的 UITextField 下显示错误

如何在 swift 2 中将 UITextField 保存到核心数据?

显示用户在Swift中的UITextfield中键入的密码

如何在 swift 2.0 中只允许 UITextfield 中的某些数字集

UITextField 的键盘不会出现在 Swift 中的第一次点击时

更改 UISearchBar 中的 UITextField 高度 - Swift 3