【问题标题】:How to find the index of an edited textfield in a tableview如何在表格视图中查找已编辑文本字段的索引
【发布时间】:2020-03-17 13:14:52
【问题描述】:

我有一个 UITableView,其中每个单元格都嵌入了 UITextField。我有一组值,我想根据编辑的 UITextField 进行更改。目前,我正在使用该功能:

func textFieldDidEndEditing(_ textField: UITextField) {
            editedValue = textField.text!
        }

但是我想要做的是设置一个通用字符串,如果用户更改 UITextField 中的文本,那么我可以索引该字符串并更改该特定值。有没有办法找到包含被编辑的 UITextField 的单元格的标签?

【问题讨论】:

    标签: ios swift xcode uitableview uitextfield


    【解决方案1】:

    在你的 cellForRowAtIndexPath 中,这样做:

    cell.yourTextField.tag = indexPath.row // so we are setting the tag of your textfield to indexPath.row, so that we can use this tag property to get the indexpath.
    cell.yourTextField.addTarget(self, action: #selector(textChanged(textField:)), for: .editingChanged)
    

    现在在你的视图控制器中声明这个函数:

    @objc func textChanged(textField: UITextField) { 
     let index = textField.tag 
     // this index is equal to the row of the textview
    }
    

    【讨论】:

      【解决方案2】:

      您可以获取 textField 的父单元格,然后找到 IndexPath

      func textFieldDidEndEditing(_ textField: UITextField) {
              if let cell = textField.superview as? UITableViewCell {
                  let indexpath = tableview.indexPath(for: cell)
                  // indexpath.row -  row index, indexpath.section - section index
              } 
          }
      

      【讨论】:

        【解决方案3】:

        首先在你的 UITableViewCell 中定义一个协议/委托

        
        protocol CustomCellDelegate: class {
            func getTextFeildData(cell: CustomCell, text: String)
        }
        
        class CustomCell: UITableViewCell {
        
            weak var delegate: CustomCellDelegate!
        
            func textFieldDidEndEditing(_ textField: UITextField) {
                delegate.getTextFeildData(cell: self, text: textField.text ?? "")
            }
        }
        
        

        在你的 cellForRowAtIndexPath 函数中设置单元格的委托:

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
            cell.delegate = self
        
            return cell
        }
        
        

        然后确认ViewController的委托方法:

        extension ViewController: CustomCellDelegate {
        
            func getTextFeildData(cell: CustomCell, text: String) {
        
                guard let tappedIndexPath = self.tableView.indexPathForCell(cell) else {return}
        
                print("Tapped IndexPath: \(tappedIndexPath)")
                print("Text Field data: \(text)")
        
                // update your model here
            }
        }
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多