问题
i need to set minimum and maximum limit value to one single textfield i.e the number should start with minimum 2 digits and maximum 5 digits here i tried some methods
-(BOOL)validatenumber:(NSString*)Number{
if ([Number length ]>=2) {
return NO;
}
return YES;
}
回答1:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSInteger inte = [textField.text intValue];
if (inte <5 && inte > 2)
return NO;
else
return YES;
}
Swift
override func textFieldShouldReturn(textField: UITextField) -> Bool {
var inte: Int = CInt(textField.text!)!
if inte < 5 && inte > 2 {
return false
}
else {
return true
}
}
回答2:
if ([amount.text length]>=2 && [amount.text length]<=5) {
}else{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"error" message:@"Plz enter the amout Min 10Rs" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
回答3:
I would first check that you can parse a number from your string, and then check the range of the number
-(BOOL)validatenumber:(NSString*)Number{
NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789,."] invertedSet];
if ([Number rangeOfCharacterFromSet:characterSet].location != NSNotFound)
{
return NO;
}
return ([Number intValue] >= 100 && [Number intValue] <= 99999);
}
Set the delegate to your UITextField. And run validate when the user finishes editing your UITextField in function func textFieldDidEndEditing(_ textField: UITextField)
. Present a popup alert to the user if validation fails
来源:https://stackoverflow.com/questions/26582453/how-to-set-minimum-and-maximum-limit-to-uitextfield