【发布时间】:2021-02-06 14:46:24
【问题描述】:
我的表格视图单元格中有一个文本字段。当我输入内容并单击提交按钮时,我想将文本保存在结构中以在其他视图控制器中使用它。但问题是,当我第一次单击提交按钮时,我的 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”。因为我的表格视图单元格中有很多文本字段,因为它是一种医疗表格。
如何解决这个问题?谁能帮帮我?
【问题讨论】:
-
在按钮操作 self.view.endEditing(true) 中添加这一行
-
当您点击按钮时,可能 textField 不会退出响应者。这就是为什么我更喜欢创建一个连接到两个事件的特定 IBAction:退出时结束和编辑结束结束。