开发者

How to set limit in text field?

开发者 https://www.devze.com 2023-03-23 13:43 出处:网络
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,

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消