swift4中的UITextfield验证-动态单元格

时间:2018-11-07 06:01:44

标签: ios swift uitableview uitextfield

我有一个表格(带有问题和文本字段的表格视图)。 它不是静态的,因为数据可能会根据用户选择的表单而改变。 因此,我将这些问题和验证约束存储在字典中。 在用户按“提交”之前,如何验证这些字段? 代码如下:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let Cell:FormTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cellformid") as! FormTableViewCell
    let dict = questions?[indexPath.row]
        Cell.form_question_label.text = dict?.question_name
        Cell.form_answer_textfield.text = dict?.answer ?? ""
        return Cell
    }

//Submit Button Action
   @IBAction func saveFormButtonPressed(_ sender: Any) {
   //Here I do operations to save a Array which contain all attended answers.

}

注意:当我按提交按钮时,用户输入的数据将保存到数据库中,但是无法完成验证,因为是否有人提出了一些问题,这些问题没有存储在数据库中,也没有附加到数组中。因此,我无法检查是否所有必填字段都已填写。

请提出一种方法。

2 个答案:

答案 0 :(得分:1)

您可以添加到您的UITextField

textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

然后验证答案:

@objc func textFieldDidChange(_ textField: UITextField) {
   //Validation
}

答案 1 :(得分:0)

尝试一下。

for view in self.view.subviews {
     if (view is UITextField) {
          var textfield = view as! UITextField
          if (textfield.text == "") {
                // execute code
          }
     }
}