我的目标是在这两个文本字段都为空时禁用完成按钮。我有顶部按钮的逻辑,但是一旦顶部文本字段“taskNameTextFIeld”至少有一个字符,就会启用完成按钮。我不希望用户能够在“timeTextField”为空时按下完成。你可以在textField()中看到我到目前为止。
import UIKit
protocol AddNewTaskViewControllerDelegate: class {
func addNewTaskViewControllerDidCancel(_ controller: AddNewTaskViewController)
func addNewTaskViewController(_ controller: AddNewTaskViewController,
didFinishAdding item: TaskData)
}
class AddNewTaskViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet weak var taskNameTextFIeld: UITextField!
@IBOutlet weak var timeTextFIeld: UITextField!
@IBOutlet weak var doneBarButton: UIBarButtonItem!
weak var delegate: AddNewTaskViewControllerDelegate?
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let oldText = textField.text! as NSString
let newText = oldText.replacingCharacters(in: range, with: string) as NSString
doneBarButton.isEnabled = newText.length > 0
return true
}
@IBAction func cancel(_ sender: Any) {
delegate?.addNewTaskViewControllerDidCancel(self)
}
@IBAction func done(_ sender: Any) {
let item = TaskData()
item.task = taskNameTextFIeld.text!
item.time = timeTextFIeld.text!
delegate?.addNewTaskViewController(self, didFinishAdding: item)
}
func textFieldShouldReturn(_ TextField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
return nil
}
override func viewDidLoad() {
super.viewDidLoad()
self.taskNameTextFIeld.delegate = self;
self.timeTextFIeld.delegate = self;
// Do any additional setup after loading the view.
}
}
答案 0 :(得分:1)
问题是您没有检查两个字段。变化:
doneBarButton.isEnabled = newText.length > 0
要对事物进行实际检查:
if taskNameTextFIeld.text.length > 0 && timeTextFIeld.text.length > 0 {
doneBarButton.isEnabled = newText.length > 0
}
另外,我建议将两个文本字段的名称更改为Field
而不是Field
。
答案 1 :(得分:0)
以下是我如何解决问题的一些细节。文本字段本身没有长度成员,因此我比较了字符数。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let oldText = textField.text! as NSString
let newText = oldText.replacingCharacters(in: range, with: string) as NSString
//doneBarButton.isEnabled = newText.length > 0
if (taskNameTextFIeld.text?.characters.count)! > 0 && (timeTextFIeld.text?.characters.count)! > 0 {
doneBarButton.isEnabled = newText.length > 0
}
return true
}