Mihai Fonoage
Mihai Fonoage

Reputation: 478

Limit number of characters in UITextField where input is from UI

I have a UITextField for which I get input from some buttons that are part of the UI (so the input does not come form the phone's virtual keyboard). I want to limit that number of characters. I tried using the shouldChangeCharactersInRange, but it only works if the input comes form the virtual keyboard, and it doesn't work if the input comes from the buttons on the UI. Is there anyway I can solve this without programmatically having to count the characters in the text field every time I want to update it?

Thank you, Mihai Fonoage

Upvotes: 4

Views: 3290

Answers (4)

iOSDevSF
iOSDevSF

Reputation: 1179

Implement the UITextField Delegate method shouldChangeCharactersInRange:

set the method to return YES when the length of the string is less than your maximum count.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

if (textField.text.length<3) {
    return YES;
}
return NO;
}

Upvotes: 3

NP Compete
NP Compete

Reputation: 2379

Since you are programmatically making changes to the UITextField once the user clicks the relevant buttons on the UI, you should keep track of the number of characters entered using a counter. Increase the value of the counter every time a relevant UI button is touched. Update the textfield only if the counter value is <= maximum allowed no. of characters.

Upvotes: 2

Jab
Jab

Reputation: 27485

There is a textRectForBounds Property

Upvotes: 0

David Sowsy
David Sowsy

Reputation: 1680

Check the length of the string property on the textField before accepting changes.

Upvotes: 0

Related Questions