如何在 Swift 中获取文本字段的索引路径

问题描述 投票:0回答:5

我在我的应用程序中使用分段的 tableView,tableView 的每一行都包含一个 textField,当

textFieldDidBeginEditing
我需要知道该 textField 的 indexPath。使用标签只能获取section或row,创建
UITextField
的扩展不允许添加变量。我怎样才能完成这项工作?

ios swift uitableview uitextfield
5个回答
4
投票

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

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
        }
    }
}

2
投票

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

您可以尝试使用

textField.superview
获取确切的cell/contentView,将其转换为
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
}

1
投票

cellForRow

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

将文本字段的标签设置为

index

textFieldDidBeginEditing

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

1
投票

获取包含文本字段的单元格的索引路径的最简单方法

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

0
投票

我不太熟悉 UITextField 委托。以我自己的方式,找到当前正在编辑的文本字段的单元格的索引路径。我创建了一个 IBAction 插座

editingTextField
,它的事件是
Editing did begin
所以每当用户单击文本字段时,都会调用此函数。另外,我创建了一个数组
var cellArray = [UITableViewCell]()
,它附加在
cellForRowAt

中的每个单元格
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier") as! CellIdentifier
        //whatever

        cellArray.append(cell)
        return cell
    }

您在 IBAction 插座中遍历此数组,并针对每个单元格检查其文本字段当前是否正在使用

textField.isEditing
进行编辑。如果实际上正在编辑文本字段,您可以使用
tableView.indexPath(for: myCell)
获取当前单元格的索引路径,其中
myCell
是当前单元格实例。

见下文:

    @IBAction func numberChange(_ sender: Any) {
        for cell in cellArray {
            let myCell = cell as! SelectExerciseNumTableViewCell
            if(myCell.numExercisesField.isEditing) {
                //indexPath is declared outside of this scope
                indexPath = tableView.indexPath(for: myCell)
            }
        }
    }

您还可以使用它来更新当前单元格中的文本,这就是我使用它的目的。我希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.