开发者

How to apply a restriction for text value in textfield? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Iphone UITextField only integer

I am new programmer in iPhone platform. I want apply restr开发者_运维知识库iction on text field that user enter only numeric value not any character. So please tell me how i apply these restriction and add done button on keyboard? So that i can use only numeric keypad.If i use only numeric pad then user enter only numeric value so how add done button in keypad? In short how i add done button on keyboard and apply restriction for character value?


The following method to ensure user can type only digit

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

    NSNumber* myNumber;
    NSString* myString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    range = NSMakeRange(0, [myString length]);
    [numberFormatter getObjectValue:&myNumber forString:myString range:&range error:nil];

    if (([myString length] > 0) && (myNumber== nil || range.length < [myString length])) {

        return NO;
    }else {
        return YES;
    }
}

Of Course, you can set

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string


You should set the textfield input type to keypad and implement UITextFieldDelegate and return NO from textField:shouldChangeCharactersInRange:replacementString: whenever a character is not in your accepted subset (0-9 and whatever punctuation marks you want to allow). This will cause the textfield to ignore any other input if pasted by the user.

As for the done button, you can either add an external button which dismisses the keyboard, or create your own input view which has a keypad and done button.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜