Enable a button in Swift only if all text fields have been filled out

前端 未结 10 610
误落风尘
误落风尘 2020-12-01 01:20

I am having trouble figuring out how to change my code to make it so the Done button in the navigation bar is enabled when my three text fields are filled out.

I cur

10条回答
  •  有刺的猬
    2020-12-01 01:28

    Xcode 9 • Swift 4

    You can addTarget to your text fields to monitor for the control event .editingChanged and use a single selector method for all of them:

    override func viewDidLoad() {
        super.viewDidLoad()
        doneBarButton.isEnabled = false
        [habitNameField, goalField, frequencyField].forEach({ $0.addTarget(self, action: #selector(editingChanged), for: .editingChanged) })
    }
    

    Create the selector method and use guard combined with where clause (Swift 3/4 uses a comma) to make sure all text fields are not empty otherwise just return. Swift 3 does not require @objc, but Swift 4 does:

    @objc func editingChanged(_ textField: UITextField) {
        if textField.text?.characters.count == 1 {
            if textField.text?.characters.first == " " {
                textField.text = ""
                return
            }
        }
        guard
            let habit = habitNameField.text, !habit.isEmpty,
            let goal = goalField.text, !goal.isEmpty,
            let frequency = frequencyField.text, !frequency.isEmpty
        else {
            doneBarButton.isEnabled = false
            return
        }
        doneBarButton.isEnabled = true
    }
    

    sample

提交回复
热议问题