如何在Swift中获取textField的索引路径

lb3vh1jj  于 2023-02-28  发布在  Swift
关注(0)|答案(5)|浏览(119)

我在我的应用中使用了一个分段的tableView,tableView的每一行都包含一个textField,当textFieldDidBeginEditing时,我需要知道该textField的indexPath。使用标签只能获取部分或行,而创建UITextField的扩展不允许添加变量。我如何才能做到这一点?

aiqt4smr

aiqt4smr1#

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

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

csga3l582#

有办法做到这一点,但它的坏设计无论如何,建议您把文本字段委托内的细胞类。
您可以尝试使用textField.superview获取精确的单元格/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
}
ygya80vv

ygya80vv3#

cellForRow

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

将textField的标记设置为index
textFieldDidBeginEditing

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

wlp8pajw4#

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

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

46scxncf5#

我不太熟悉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 outlet中迭代该数组,并检查每个单元格的文本字段当前是否正在使用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)
            }
        }
    }

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

相关问题