Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I limit text lengths for different UITextFields in Swift?

I have an iOS Xcode 7.3 Swift2 project I'm working on. It has different UITextFields that are limited to 3 digits, specifically only numbers. They are assigned to the UITextFieldDelegate and it's working well.

Here is where I limit them:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text else { return true }
    let newLength = text.characters.count + string.characters.count - range.length
    let limitLength = 3
    if newLength > limitLength {
        return false
    }

    let numberOnly = NSCharacterSet.init(charactersInString: "0123456789")
    let stringFromTextField = NSCharacterSet.init(charactersInString: string)
    let strValid = numberOnly.isSupersetOfSet(stringFromTextField)

    return strValid
}

However, some of the UITextFields need to be limited to numbers still AND also limited to a single digit, how can I institute this in the section above, only for those specific UITextFields?

The names of the UITextFields that need to be single digits are:

widthInches
lengthInches

I tried placing this after the first guard section with no luck:

guard let text2 = widthInches.text else { return true }
let newLength2 = text2.characters.count + string.characters.count - range.length
let limitLength2 = 3
if newLength2 > limitLength2 {
    return false
}
like image 245
ChallengerGuy Avatar asked Jun 08 '16 16:06

ChallengerGuy


1 Answers

You can also try this code for limit textfield

actually i am using here textfield tag. Because custom textfield. If you using custom textfield like TextfieldEffect in this condition tag will help you for limit of Textfield.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{
        
        if textField.tag == txtCountryCode.tag{
            let maxLength = 4
            let currentString: NSString = textField.text!
            let newString: NSString =
            currentString.stringByReplacingCharactersInRange(range, withString: string)
            return newString.length <= maxLength
        }

        
        if textField.tag == txtMobileNumber.tag{
            let maxLength = 10
            let currentString: NSString = textField.text!
            let newString: NSString =
            currentString.stringByReplacingCharactersInRange(range, withString: string)
            return newString.length <= maxLength
        }
        
        return true
    }

I hope this will help you.

like image 134
Anand Nimje Avatar answered Oct 01 '22 04:10

Anand Nimje