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

前端 未结 10 783
误落风尘
误落风尘 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:27

    I went ahead and abstracted this out a bit into a helper class that one can use for their swift project.

    import Foundation
    import UIKit
    
    class ButtonValidationHelper {
    
      var textFields: [UITextField]!
      var buttons: [UIButton]!
    
      init(textFields: [UITextField], buttons: [UIButton]) {
    
        self.textFields = textFields
        self.buttons = buttons
    
        attachTargetsToTextFields()
        disableButtons()
        checkForEmptyFields()
      }
    
      //Attach editing changed listeners to all textfields passed in
      private func attachTargetsToTextFields() {
        for textfield in textFields{
            textfield.addTarget(self, action: #selector(textFieldsIsNotEmpty), for: .editingChanged)
        }
      }
    
      @objc private func textFieldsIsNotEmpty(sender: UITextField) {
        sender.text = sender.text?.trimmingCharacters(in: .whitespaces)
        checkForEmptyFields()
      }
    
    
      //Returns true if the field is empty, false if it not
      private func checkForEmptyFields() {
    
        for textField in textFields{
            guard let textFieldVar = textField.text, !textFieldVar.isEmpty else {
                disableButtons()
                return
            }
        }
        enableButtons()
      }
    
      private func enableButtons() {
        for button in buttons{
            button.isEnabled = true
        }
      }
    
      private func disableButtons() {
        for button in buttons{
            button.isEnabled = false
        }
      }
    
    }
    

    And then in your View Controller just simply init the helper with

    buttonHelper = ButtonValidationHelper(textFields: [textfield1, textfield2, textfield3, textfield4], buttons: [button])
    

    Make sure you keep a strong reference at top to prevent deallocation

    var buttonHelper: ButtonValidationHelper!
    

提交回复
热议问题