UITextField should have only positive number

前端 未结 5 1680
执念已碎
执念已碎 2021-01-07 06:09

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

5条回答
  •  没有蜡笔的小新
    2021-01-07 06:48

    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

提交回复
热议问题