问题
I'm having trouble setting a maximum length for the content of a text field. The process I took was implementing the UITextFieldDelegate in my header file. I then defined (and then called) this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 5) ? NO : YES;
}
This was a method that I got by suggestion here on the site. I've also tried this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [zipCode.text length] + [string length] - range.length;
return (newLength > 5) ? NO : YES;
}
"zipCode" is the the outlet that I connected to the text field. Each time I've changed the code I've made sure to reconnect the outlet. I have a feeling it's a very simple thing that I'm missing. Apologies if this is a little convoluted, I have a lot to learn! Thanks.
回答1:
Try this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
return (zipCode.text.length + string.length <= 5);
}
Then, in the viewDidLoad method:
- (void)viewDidLoad {
zipCode.delegate = self;
//.....
[super viewDidLoad];
}
来源:https://stackoverflow.com/questions/7670018/trouble-setting-a-maximum-length-for-a-text-field