Search code examples
iosswiftuitextfieldcharacterstring-length

How to get range of textField text till 6 characters?


I've a UITextField for entering pincode number.
My requirement is when textField character range reach to 6th character then I've to do server validation and I have to put the data in labels. If character range is less than 5 then I will pass nil value.

Below is my code :-

//TextField character range
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if textField == pinCode
    {
        guard let text = textField.text else { return  true }

        let newLength = text.characters.count + string.characters.count - range.length
        if(5 >= newLength)
        {
            print(newLength)
        }

        else
        {
            if newLength == 6
            {
                serverValidation()

                print(textField.text!)
                setFields(city: "Ajmer", state: "Rajasthan", country: "India")
                return newLength <= 6
            }
            else
            {
                 return newLength <= 6
            }
        }

    }

    return true
} 

My problem is when (newLength == 6) then I'm getting textField text of 5 characters only. I mean if suppose zip code is 560068 then text I'm getting 56006 only. (But I've to do server validation in that condition only for 6 characters zip code)

So if (newLength == 6) then how can I get 6 characters in text field, and then I can do server validation here only.

I'm new in swift.

Thanks


Solution

  • shouldChangeCharactersIn will get called prior to getting the actual text in the UITextField

    This is how you get the full text from that UITextField

    let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
    

    Edit

    this is how you can use it

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
        if textField == pinCode
        {
            guard let text = textField.text else { return  true }
    
            let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
            let newLength = newString.characters.count
    
            if(5 >= newLength)
            {
                print(newLength)
            }
    
            else
            {
                if newLength == 6
                {
                    serverValidation()
    
                    print(newString)
                    setFields(city: "Ajmer", state: "Rajasthan", country: "India")
                    return newLength <= 6
                }
                else
                {
                     return newLength <= 6
                }
            }
    
        }
    
        return true
    }