textFieldDidEndEditing 不会在 swift

问题描述

我的 tableview 单元格中有一个文本字段。当我输入内容并单击提交按钮时,我想将文本保存在结构中以在其他视图控制器中使用它。但问题是,当我第一次点击提交按钮时,我的 textFieldDidEndEditing 函数没有调用,所以我无法将值分配给结构。

我的代码是-

   func textFieldDidEndEditing(_ textField: UITextField) 

{
        let position: CGPoint = textField.convert(CGPoint.zero,to: self.tableView)
       
        if let indexPath = self.tableView.indexPathForRow(at: position)
        {
           
                
           if let cell: InsuranceinformationTableViewCell = self.tableView.cellForRow(at: indexPath) as? InsuranceinformationTableViewCell{
            
            if textField == cell.policyHolderFullNameTextField{
                insuranceModel.policuHolderFullName = textField.text
            }
                        
        }
}
}

提交按钮操作-

    @IBAction func SubmitButtonAction(_ sender: UIButton) {   
 
            if (insuranceModel.policuHolderFullName == nil) {
               showAlert(withTitle: "Data Missing",withMessage: "Policy holder fullName field cannot be empty")
               return
           }
                        
            let encoder = JSONEncoder()
           if let encoded = try? encoder.encode(insuranceModel) {
               let defaults = UserDefaults.standard
               defaults.set(encoded,forKey: "SavedInsuranceinformation")
            
        self.navigationController?.pushViewController(StockAndBillPreviewViewController.instantiateStockAndBillPreviewViewController(),animated: true)
 }
 func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 case TableSection.insuranceType.rawValue:
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "InsuranceinformationTableViewCell",for: indexPath) as? InsuranceinformationTableViewCell else {
                return UITableViewCell()
            }
            
            cell.policyHolderFullNameTextField.delegate = self
}

当我单击提交按钮时,它向我显示错误消息。 在这里我不想使用“UITextField,shouldChangeCharactersIn range”。因为我的 tableview 单元格中有很多文本字段,因为它是一种医学表格。

如何解决这个问题?有人可以帮我吗?

解决方法

1.这可能发生的最常见原因之一是您可能没有分配文本视图委托方法。 因此,只需将“UITextViewDelegate”添加为符合您的表格视图单元格,然后在故事板中设置委托。 2. 如果您已经完成了第一种方法但它仍然不起作用,那么您可以按照最基本的方法在单击提交按钮时获取文本字段中的任何内容。 在您的代码中的任何一点,您都可以通过“textfield.text”访问文本字段中的文本, 只需创建文本字段的出口并在提交按钮中使用 youroutletname.text 以保存在结构中。

,

我不确定 textFieldDidEndEditing 在这种情况下是否调用。我使用以下方法:

(1) 使用 UITextView 定义自定义单元格并为 UITextViewDelegate textViewDidChange 方法制作单元格委托

(2) 创建自定义单元格委托协议以将文本更改发送到 TableViewController

(3) 为自定义单元格制作 TableViewController 委托并记录控制器内 UITextView 文本的所有更改