防止UITextField标记被覆盖

时间:2019-02-21 05:10:46

标签: ios swift uitableview uitextfield

我有一个使用UITextField的自定义单元格。我将数据传递给tableView进行处理。实际上,您可以有多行,所以我用indexPath.row

来跟踪它
// I reuse this in all cells
struct Label {
 static func textField(cell: UITableViewCell, f: Selector, tag: Int: 1) -> UITextField {
   let t = UITextField()
   t.tag = tag
   t.addTarget(cell, action: f, for: .editingChanged)
   [...] // placeholder, fonts etc
   return t
 }
}

在课堂上:

// cellForRowAt
let foo = tableView.dequeueReusableCell(withIdentifier: "foo") as! foo

foo.textTyped = { sender in
  let textFieldPosition = sender.convert(sender.bounds.origin, to: self.tableView)
  let indexPath = self.tableView.indexPathForRow(at: textFieldPosition)

  let field = sender.tag // the int assigned inside foo's cell

  print("FIELD IS: ", field) // I should see the int for the field I'm typing in

  // I keep track of the row with indexPath.row
  // I need to attach it to sender
  sender.tag = indexPath!.row // But, this changes field

  // I use a switch statement based on field
  switch field {
  case 4:
   sender.addTarget(self, action: #selector(self.fooTyped /* omitted here */), for: .editingChanged)
   [...]
  }
}

在第一种类型上,我看到正确的int字段,然后将其更改为indexPath.row的值

单元格:

var textTyped: ((UITextField) -> Void)?

@objc func fieldTyped(sender: UITextField) -> Void {
  textTyped?(sender)
}

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
  super.init(style: style, reuseIdentifier: reuseIdentifier)

 // More than one of these but with a unique variable to setup its constraints:
let foo1 = Label.textField(cell: self, f: #selector(fieldTyped), tag: 4) 

// foo2 = [...] with tag: 9 (for example)
}

此设置的一个很好的例子是iOS设备上的“联系人”应用程序。点击“添加地址”,您会看到一个单元格。再次点击,您将看到另一个。我用indexPath.row来跟踪它。一行有许多UITextField。问题是,将indexPath.row分配给sender.tag会抛出我手动设置的UITextField标签,即tag = 4。它显示“ 0”

我很乐意发布更多代码,但这只是我的那部分代码。我希望“字段”会在我在任何文本字段中键入时打印该标签。

1 个答案:

答案 0 :(得分:0)

这是对我有用的,我愿意改进。

我需要将indexPath移至函数Im调用fooTyped,然后获得以下位置:

// cellForRowAt
let foo = tableView.dequeueReusableCell(withIdentifier: "foo") as! foo

foo.textTyped = { sender in
  // I use a switch statement based on field
  // sender.tag would determine Street1, Street2 etc
  switch sender.tag {
  case 4:
   sender.addTarget(self, action: #selector(self.fooTyped /* omitted here */), for: .editingChanged)
   [...]
  }
}

TableView类

// get row position
fileprivate func getRowPositionFromSender(sender: UITextField) -> Int {
    let textFieldPosition = sender.convert(sender.bounds.origin, to: self.tableView)
    let indexPath = self.tableView.indexPathForRow(at: textFieldPosition)
    return (indexPath?.row)!
}

// Then use it in fooTyped (street1)
@objc func fooTyped(sender: UITextField) {
    let position = getRowPositionFromSender(sender: sender)
    print(position) // This is what Im after
}

// Similar func for Street2
[...]