我希望textField文本在我确认之前大于0
我参考了这个example
但它不起作用
如何更好地更改以下代码?
有没有更简单的方法来检查看守?
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)
}
}
}
答案 0 :(得分:0)
我想你想知道textField中的文本是否为空? 在这种情况下,您应该使用此检查:
if let text = textField.text,!text.trimmingCharacters(in: .whitespaces).isEmpty {
//The use the text here
}
这将首先检查TextField中是否有任何文本。当该文本仅包含空格(“”)时,文本将不是nil和text.count> 0也会过去。所以在这种情况下我们使用trimmingCharacters(in:)
函数来删除这些空格。 isEmpty
检查然后判断修剪后的String是否为空。
在我的例子中,我想在if子句中使用字符串,所以我使用了“!”在isEmpty
之前 - 检查。