0

I want textField text to be greater than 0 before I can confirm

I have reference to this example

but it's not work

How can I change the following code better?

Is there an easier way to check the guard let?

func addNewList() {
    let addAlert = UIAlertController(title: "新增列表", message: "請輸入列表名稱", preferredStyle: .alert)
    addAlert.addTextField { (textfied: UITextField) in
        textfied.placeholder = "列表名稱"
        textfied.addTarget(addAlert, action: #selector(addAlert.textDidChanged), for: .editingChanged)
    }

    let confirm = UIAlertAction(title: "確認", style: .default) { (action: UIAlertAction) in

        guard let name = addAlert.textFields?.first?.text else { return }

        let newList = List(name: name, completed: false)
        self.item?.lists.append(newList)

        let indexPath = IndexPath(row: self.listTableView.numberOfRows(inSection: 0), section: 0)
        self.listTableView.insertRows(at: [indexPath], with: .left)
    }

    let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)

    addAlert.addAction(cancel)
    confirm.isEnabled = false
    addAlert.addAction(confirm)

    self.present(addAlert, animated: true, completion: nil)
}

extension UIAlertController {
    func checkItemName(_ text: String) -> Bool{
        return text.count > 0
    }

    @objc func textDidChanged() {
        if let name = textFields?.first?.text, let action = actions.last {
           action.isEnabled = checkItemName(name)
        }
    }
}
Daniel
  • 3,188
  • 14
  • 34
Venson
  • 1
  • "textField text to be greater than 0" You mean non-empty field? Or you allow only integers and want a numerical value? – Larme Jun 12 '18 at 14:07
  • What about it doesn't work? Does it return true for textfields you think are empty but are really not (like only spaces)? – Daniel Jun 12 '18 at 14:11
  • I want any text in the text field, But not included " " – Venson Jun 13 '18 at 01:37

1 Answers1

0

I think you want to know whether the text in the textField is empty or not? In this case you should use this check:

if let text = textField.text,!text.trimmingCharacters(in: .whitespaces).isEmpty {
  //The use the text here
}

This would first check if there is any text in the TextField. When this text contains just consist of whitespaces (" ") the text won't be nil and text.count > 0 would also pass. So in that case we use the trimmingCharacters(in:) function, which removes these whitespaces. The isEmpty check then says whether the trimmed String is empty or not.

In my example, I want to use the string in the if clause so I used the "!" before the isEmpty-check.

Marcel T
  • 659
  • 1
  • 7
  • 28