aspenfox
aspenfox

Reputation: 1

Limiting Characters in UITextField? - Swift/Xcode

I'm new to developing and I am trying to limit the number of characters that can be entered in a textfield, with the most recent version of Swift. I have tried to follow several different tutorials and have checked out a few different answers around the site, but I am not having much luck.

Currently, I have this entered in my swift file:

@IBAction func InfoTextFieldLimit(sender: UITextField) {

        self.InfoTextField.delegate = self

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

            let currentCharacterCount = textField.text?.characters.count ?? 0
            if (range.length + range.location > currentCharacterCount) {

                return false
            }

            let newLength = currentCharacterCount + string.characters.count - range.length
            return newLength <= 10
        }
    }

...I'm not getting any errors, but nothing seems to be happening when I run the app.

I have also tried at least 3 other methods that I didn't bother copying. (but can provide on request)

Can anybody tell me what I'm doing wrong and point me in the right direction? Would be much appreciated! ...I feel like there's a good chance I might be overlooking something that's obvious.

I am also going to want to do this with a textview down the road, how would that be different?

Upvotes: 0

Views: 4036

Answers (2)

Mathews
Mathews

Reputation: 743

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

Also make sure you have set the delegate of the UITextField to the UIViewController

Upvotes: 1

Neil Shweky
Neil Shweky

Reputation: 893

I originally had this code in objective-c:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 4) ? NO : YES;
}

I tried converting it to swift, let me know if it works... You have to use the UITextFieldDelegate method.

func textField( textField:UITextField,shouldChangeCharactersInRange range:NSRange,replacementString string:NSString)->Bool{
var newLength:NSUInteger = textField.text.length + string.length  - range.length 

return null(newLength >  4 )?false:true

}

Upvotes: 0

Related Questions