I have a question about implementing button deactivation by condition in iOS.

Asked 2 years ago, Updated 2 years ago, 34 views

Hello, we are implementing the login button to activate from 4 characters in the password text field.


func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if passwordField.text!.count < 3 || (range.location == 3 && range.length == 1)  {
            loginButton.isEnabled = false
        } } else {
            loginButton.isEnabled = true
        }
        print (passwordField.text!, range.location, range.length) // This part was created for verification.
        return true
    }

This allows the password field to activate the button from 4 digits.

Due to the nature of NSRange, range.location and range.length are included in the condition in preparation for erasing characters.

But I have a few questions because of that confusing method.

1) Isn't the count of a normal string starting from 1? Why does count start with zero in this method? Is it because of the parameters of the NSRange type?

2) TextField is disabled when characters are increased from 2 to 3 (this is normal), but suddenly activated when deleted from 3 to 2.

Why is that? If you take a log with print, shouldn't it be deactivated by satisfying the if statement because the location part is 2 and the length part is 1?

3) This is the most important question. Do we have to make a password validation like this? LOL I think I shoveled for 6 hours before I really knew this concept.

I'm sure there's another easy way. I would appreciate it if you could let me know if there is any other way. (Crying)

I think I asked a question with Jung-gu District heating because I am not good at writing, but if you don't understand the question or if you have anything I'm missing, I'd appreciate it if you could let me know.

swift ios

2022-09-22 16:07

1 Answers

The textField (_:shouldChangeCharactersIn:replacementString:) is invoked before the text in the textfield changes. This is because it is for returning whether to reflect the change to boolean. That's why problems one or two occur.

If you want to check the length, use UIControl.Use Event.editingChanged. You can use it like textView DidChange (_:) in UITextView.

If you have to deal with it with shouldChangeCharacters, You can use the text of the text field by repositioning it to NSString.replaceCharactersInRange using the parameter.


2022-09-22 16:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.