Anilkumar iOS Developer
Anilkumar iOS Developer

Reputation: 3755

How to restrict double/single space for TextField in Swift 3 iOS

I have login page in my iOS app which is developing by Swift language. In that first letter should not be with single/double space and after user enters text it should allow single space, not allow double space and need to set the limit for text length.

I want to restrict the user while tapping single/double space while starting time entering text and need to allow single space after enters first letter in textfield

I am able to do either one of single/double, but not working as per my requirement.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    //for double space restrict
    if (range.location > 0 && (textField.text?.characters.count)! > 0) {
        //Manually replace the space with your own space, programmatically
        //Make sure you update the text caret to reflect the programmatic change to the text view
        //Tell Cocoa not to insert its space, because you've just inserted your own
        return false
    }else {
        if textField.tag == 1 || textField.tag == 2 { //restrict text length
            guard let text = textField.text else { return true }
            let newLength = text.characters.count + string.characters.count - range.length
            return newLength <= limitLengthForTextField
        }
    }

    return true 
}

Can anyone give suggestions. Thanks

Upvotes: 1

Views: 7628

Answers (9)

Umair Ali
Umair Ali

Reputation: 836

Swift 5.0

Only allow single space in textField text change with Error handling:

func textField(textField: UITextField, 
               shouldChangeCharactersInRange 
               range: NSRange, replacementString string: String) -> Bool {
    let (isValid, errorMessage) =  validateSpacesInTextChange(newText: string, existingText: textField.text!, in: NSRange) 
    return isValid
}

func validateSpacesInTextChange(newText: String,
                                existingText: String,
                                in range: NSRange) -> (Bool, errorMessage: String?) {
     let range = newText.rangeOfCharacter(from: .whitespaces)
        
     let textNotStartWithSpace = !(existingText.isEmpty && range != nil)
     guard textNotStartWithSpace else { return (false, "Space not allowed at the Begning") }
        
     let notContainTwoSpaces = !(!existingText.isEmpty && existingText.last == " " && range != nil)
     guard notContainTwoSpaces else { return (false, "Only single space allowed") }
        
     return (true, nil)
}

Upvotes: 0

Anilkumar iOS Developer
Anilkumar iOS Developer

Reputation: 3755

I found answer finally for my requirement

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

    //for double space restrict
    let str = textField.text
    if str?.characters.count == 0 && string == " " {
        return false
    } else if (str?.characters.count)! > 0 {
        if str?.characters.last == " " && string == " " {
            return false
        } else {
            if textField.tag == 1 || textField.tag == 2 { //restrict text length
                guard let text = textField.text else { return true }
                let newLength = text.characters.count + string.characters.count - range.length
                return newLength <= limitLengthForTextField
            }
        }
    }
    return true 
}

Upvotes: 0

Harikant Amipara
Harikant Amipara

Reputation: 191

Swift 4.1

Just simple with Single line of code you can stop whitespace

For All Textfield

 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        textField.text = textField.text?.replacingOccurrences(of: " ", with: "")
        return true
    }

For Single Textfield

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if textField == txtid
    {
        textField.text = textField.text?.replacingOccurrences(of: " ", with: "")
    }
    return true
}

Upvotes: 0

Samrat Pramanik
Samrat Pramanik

Reputation: 201

func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if range.location == 0 && string == " " {
       return false
   } else if range.location > 1 && textField.text?.characters.last == " " && string == " " {
       return false
   }else{
       return true
   }
}

Hi, Anli please try this it will solve your problem.

Upvotes: 0

Mohammad Sadiq
Mohammad Sadiq

Reputation: 5241

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let rawString = string
     let range = rawString.rangeOfCharacter(from: .whitespaces)
    if ((textField.text?.characters.count)! == 0 && range  != nil)
    || ((textField.text?.characters.count)! > 0 && textField.text?.characters.last  == " " && range != nil)  {
        return false
    }
return true
}

Upvotes: 2

Akhilrajtr
Akhilrajtr

Reputation: 5182

try this

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let result = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) ?? string
    let text = result as String
    if (text.range(of: "^(?i)(?![ ])(?!.*[ ]{2})[A-Z. ]*$", options: .regularExpression) != nil) {

        return true
    }
    return false
}

If you need to restrict total length update the regex to ^(?i)(?![ ])(?!.*[ ]{2})[A-Z. ]{1,10}$ for 10 chars. Update the length as required.

Upvotes: 2

Kavin Kumar Arumugam
Kavin Kumar Arumugam

Reputation: 1832

Try This Code:

//TextField Validation
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    {
        if(textField == UserNameText)
        {
            if range.location == 0 && string == " "
            {
                return false
            }
            return true
        }
        else if(textField == PasswordText)
        {
            if range.location == 0 && string == " "
            {
                return false
            }
            return true
        }
        else
        {
            return true
        }
    }

It Wont allow users to give space at first letter. For Example if you need to set limit for username field and its limit is 10 characters means use this code:

//TextField Validation
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
        {
            if(textField == UserNameText)
            {
                if range.location == 0 && string == " "
                {
                    return false
                }
                else if range.length + range.location > (self. UserNameText.text?.characters.count)!
                {
                     return false
                }
                let NewLength = (self.let NewLength = (self.userEmailTxt.text?.characters.count)! - range.length
                return NewLength <= 9
            }
            else if(textField == PasswordText)
            {
                if range.location == 0 && string == " "
                {
                    return false
                }
                return true
            }
            else
            {
                return true
            }
        }

Upvotes: 3

Sudipto Roy
Sudipto Roy

Reputation: 6795

It works !

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
       if (string == " " || string == "  ") &&  range.location == 0
       {
           return false
       }

       return true
}

Upvotes: 0

Paras Gorasiya
Paras Gorasiya

Reputation: 1351

Please check this code.

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

    let trimmedString = textField.text?.trimmingCharacters(in: .whitespaces)
    if (trimmedString.length == 0)
        return false

    //for double space restrict
    if (range.location > 0 && (textField.text?.characters.count)! > 0) {
        //Manually replace the space with your own space, programmatically
        //Make sure you update the text caret to reflect the programmatic change to the text view
        //Tell Cocoa not to insert its space, because you've just inserted your own
        if string.range(of:" ") != nil {
            return false
        }
        return true
    }else {
        if textField.tag == 1 || textField.tag == 2 { //restrict text length
            guard let text = textField.text else { return true }
            let newLength = text.characters.count + string.characters.count - range.length
            return newLength <= limitLengthForTextField
        }
    }

    return true
}

And your code for restricting textfield length should work fine as it is for textfields with tag 1 & 2.

Upvotes: 0

Related Questions