【问题标题】:How can I get the IndexPath of a textField in Swift如何在 Swift 中获取 textField 的 IndexPath
【发布时间】:2021-01-03 22:03:01
【问题描述】:

我在我的应用程序中使用了一个分段的 tableView,tableView 的每一行都包含一个 textField,当textFieldDidBeginEditing 我需要知道那个 textField 的 indexPath。使用标签只能获取节或行,而创建UITextField 的扩展名不允许您添加变量。我怎样才能完成这项工作?

【问题讨论】:

  • 如果您的 UITableView 单元格中有 UITextFields,那么我相信您的 didSelect(:IndexPath) 存根应该在 UITextField 成为第一响应者时触发。先探索一下。如果这不起作用,请尝试使用 Closure 覆盖 UITextField 类,以便在成为第一响应者时执行。
  • 您可以继承 UITextField 并向其添加 indexPath 属性。 dropbox.com/s/2yq641m7g5v6a7g/…

标签: ios swift uitableview uitextfield


【解决方案1】:

我喜欢从文本字段走到单元格并询问表格视图的索引路径。

extension UIResponder {
    func next<T:UIResponder>(ofType: T.Type) -> T? {
        let r = self.next
        if let r = r as? T ?? r?.next(ofType: T.self) {
            return r
        } else {
            return nil
        }
    }
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    if let cell = textField.next(ofType: MyCell.self) {
        if let ip = self.tableView.indexPath(for:cell) {
           // whatever
        }
    }
}

【讨论】:

  • next 是否等同于 superView?我以前从未使用过。
  • @Tj3n 它是响应者链,它包含视图层次结构
【解决方案2】:

有办法做到这一点,但无论如何这是糟糕的设计,建议您将文本字段委托放在单元格类中。

您可以尝试使用textField.superview 获取确切的单元格/内容视图,将其转换为MyTableViewCell,然后使用tableView.indexPath(for: cell) 获取索引。

不需要标签。

例子:

var view: UIView = textField
while !view.isKind(of: UITableViewCell.self), let superView = view.superview {
    view = superView
}
if let view = view as? MyTableViewCell {
   //Do sth
}

【讨论】:

  • 这不会按原样编译,因为view 被隐式键入为 UITextField。您必须将其显式键入为 UIView。
【解决方案3】:

cellForRow

var section = indexPath.section + 1
var row = indexPath.row + 1
index = Int("\(section)0\(row)")!

将 textFields 的标签设置为 index

textFieldDidBeginEditing

let indexString = "\(textField.tag)"
let parts = indexString.components(separatedBy: "0")
let row = Int(parts[1])! - 1
let section = Int(parts[0])! - 1

【讨论】:

    【解决方案4】:

    获取包含文本字段的单元格的 indexPath 的最简单方法

    func getIndexPathFromView(_ sender : UIView) -> IndexPath? {
        let point = sender.convert(CGPoint.zero, to: self.tblView)
        let indexPath = self.tblView.indexPathForRow(at: point)
        return indexPath
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-25
      • 1970-01-01
      • 2014-07-27
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多