How to set limit in text field?
can any body tell me how to set the limit for words to enter in a text field in objective-c?
In my case i have a registration form and in registration form every user have to enter username
, password
, email
and phone no.
and now i have to restrict the user t开发者_如何转开发o enter a name of maximum 15 characters.
can any one tell me how i can do this?
You are able to restrict number of inputs in UITextField
both following ways.
First of all, set relevant UIViewController
as a delegate object to UITextField
yourTextField.delegate = self;
Then add the following code snippet to your UIViewController
.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([textField.text length]<15) {
return YES;
}
return NO;
}
Or you can define UITextFieldDelegate
protocol in your UIViewController
interface
@interface YourViewController()<UITextFieldDelegate>
// YourViewController.m
@end
and then implement the following shouldChangeCharactersInRange
task in your class.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 15) ? NO : YES;
}
Try this:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *textFieldText = [textField.text stringByReplacingCharactersInRange:range withString:string];
if ([textFieldText length] > 15)
{
return NO;
}
return YES;
}
精彩评论