问题
I have to allow values less than 190 in uitextfield
while entering itself.we should not allow user to enter 1
to 9
digits after 19
.
Can anyone please provide me some info regarding this.
I tried the below code.But it's allowing more than 190
.
if countElements(textField.text!) + countElements(string) - range.length < 4
{
var floatValue : Float = NSString(string: toString(textField.text)).floatValue
return floatValue < 190.0
}
回答1:
How i would do it is set the the uiviewcontroller containing the uitextfield as the delegate of the text field. Then add this:
//If number of characters needs to be less than 190
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if([newString length]>190){
return NO;
}
return YES;
}
//If value needs to be less than 190
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if([newString intValue]>190){
return NO;
}
return YES;
}
回答2:
You can use UITextFieldTextDidChangeNotification and then do the value check in the selector for the notification. Here is an example of implementation I verified in Xcode:
#import "ViewController.h"
@interface ViewController () <UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITextField *textField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.textField.delegate = self;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange) name:UITextFieldTextDidChangeNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)textFieldDidChange
{
if ([self.textField.text length] > 3) {
NSString* subString = [self.textField.text substringWithRange:NSMakeRange(0, 3)];
self.textField.text = subString;
}
if ( [self.textField.text intValue] > 190)
{
NSString* subString = [self.textField.text substringWithRange:NSMakeRange(0, 2)];
self.textField.text = subString;
}
}
@end
来源:https://stackoverflow.com/questions/27916943/how-to-not-allow-the-user-to-enter-a-value-more-than-190-in-uitextfield