我在我的应用程序中使用分段的 tableView,tableView 的每一行都包含一个 textField,当
textFieldDidBeginEditing
我需要知道该 textField 的 indexPath。使用标签只能获取section或row,创建UITextField
的扩展不允许添加变量。我怎样才能完成这项工作?
我喜欢从文本字段走到单元格,并向表视图询问它的索引路径。
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
}
}
}
有办法做到这一点,但无论如何都是糟糕的设计,建议您将文本字段委托放在单元格类中。
您可以尝试使用
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
}
在
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
获取包含文本字段的单元格的索引路径的最简单方法
func getIndexPathFromView(_ sender : UIView) -> IndexPath? {
let point = sender.convert(CGPoint.zero, to: self.tblView)
let indexPath = self.tblView.indexPathForRow(at: point)
return indexPath
}
我不太熟悉 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)
}
}
}
您还可以使用它来更新当前单元格中的文本,这就是我使用它的目的。我希望这有帮助!