UITextField should have only positive number

被刻印的时光 ゝ 提交于 2019-11-30 19:20:19

问题


I need to validate a UITextField. I want only positive integers to be entered in it. How can I achieve that?


回答1:


Add UITextFieldDelegate,and add this code to your class

#define LEAGELNUM @"0123456789"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:LEAGELNUM] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]     componentsJoinedByString:@""];
        BOOL basicTest = [string isEqualToString:filtered];
        return basicTest;
}

LEAGELNUM means you can only write these words




回答2:


I'd set up a NSNumberFormatter to retrieve a number from the UITextFields text property. Then get an intValue from the number and check whether it's >= 0.

Update:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

[formatter setLocale:[NSLocale currentLocale]];

NSNumber *number = [formatter numberFromString:[textField text]];

[formatter release];

This should get you going. I'm not on my development machine right now so I can't test run it, maybe you need to do one or two more lines of setup. Please refer to the reference library (I posted the link above) for the available options.




回答3:


Set delegate to your UITextField ivar. Set keyboardType property to UIKeyboardTypeNumberPad Write this code.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{  
    if ([string isEqualToString:@"-"]){  
        return NO;  
    }  

    return YES;  
}



回答4:


From the top of my head:

Convert the string into a integer using [textField.text intValue] and check it is positive. I would do it in the - (BOOL)textFieldShouldEndEditing:(UITextField *)textField method from the UITextFieldDelegate protocol.

Cheers




回答5:


Use logic of this answer Toastor

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if (string.characters.count == 0) {
        return true
    }
    /// check number is postive
    if (textField == self.txtPay) {
        let formatter = NSNumberFormatter()
        formatter.locale = NSLocale.currentLocale()
        let findalString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
        let number = formatter.numberFromString(findalString)
        return number?.integerValue > 0
    }

    return true
}


来源:https://stackoverflow.com/questions/6954382/uitextfield-should-have-only-positive-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!