How can I disable a button until text in all UITextFields has been entered in swift?

旧街凉风 提交于 2020-01-02 23:59:13

问题


I need a way to disable the save button until text has been entered in all of the required text boxes? I am developing the application in Swift and I have found lots of answers in Objective-c. As I have absolutely now Objective-c knowledge, I am unable to work out what it means.

Does anybody have a solution for this which can be done in Swift?

I know how to enable/disable a button. I also know how to check if a text field is empty. I'm just not sure how to make it so that my code is always checking to see if it is empty or not. I have tried a while loop but as I expected, this froze everything.


回答1:


Listing one of the ways to achieve this:

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var button: UIButton!

    //Need to have the ViewController extend UITextFieldDelegate for using this feature
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        // Find out what the text field will be after adding the current edit
        let text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)

        if !text.isEmpty{//Checking if the input field is not empty
            button.userInteractionEnabled = true //Enabling the button
        } else {
            button.userInteractionEnabled = false //Disabling the button
        }

        // Return true so the text field will be changed
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        //Setting the Delegate for the TextField
        textField.delegate = self
        //Default checking and disabling of the Button
        if textField.text.isEmpty{
            button.userInteractionEnabled = false // Disabling the button
        }
    }
}

Reference Link for the above solution




回答2:


Despite of all the comments given so far and to not blow up the comment area further, I try to give some hints on how to solve your problem:

  • Put all the textfields in an outlet collection
  • Set the delegate of all textfields to your viewController
  • implement the delegate's didEndEditing method and within that method iterate over the outlet collection to check each textfield for its input

Note that this is only ONE way to implement that but you might get the idea.




回答3:


Use the textfield's delegate methods (or the target-action pattern) to check the conditions required for the user to proceed. If they're met, enable the button.



来源:https://stackoverflow.com/questions/29448185/how-can-i-disable-a-button-until-text-in-all-uitextfields-has-been-entered-in-sw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!