How to limit text length to fit width of dynamically created UITextField
ios, ios6, objective-c, uitextfield, xcode
Solution
You can start from this code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *text = textField.text;
text = [text stringByReplacingCharactersInRange:range withString:string];
CGSize textSize = [text sizeWithFont:textField.font];
return (textSize.width < textField.bounds.size.width) ? YES : NO;
}
after ios 7 it changes sizeWithFont to sizeWithAttributes.
Here is the code with changes:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *text = textField.text;
text = [text stringByReplacingCharactersInRange:range withString:string];
CGSize textSize = [text sizeWithAttributes:@{NSFontAttributeName:textField.font}];
return (textSize.width < textField.bounds.size.width) ? YES : NO;
}
Problem
I have dynamically created `UITextFields` which have different widths and font sizes. I know how to limit length of text in `UITextField`, but I can do this only with fixed characters number. What I need is dynamically limit characters number to fit certain `UITextFields`. I suppose that every time new character is typed I should use `CGSize` and get text length for the certain font size than compare it with UITextField width and limit the characters number if it exceeded `UITextField` width. Unfortunately I am not sure how to start it. Does anyone know any code snippets that could help me?