Ben Call Ben Call - 17 days ago 5
Objective-C Question

Backspace not working when implementing shouldChangeCharactersInRange method - iPhone Dev

Problem... I have a string of allowable characters "0123456789." How do I also allow the backspace from the keyboard... when I implement the code from below... the backspace key no longer works... How can I fix this?

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

NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];

return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);

}

Answer
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];

    if (range.length == 1){
        return YES;
    }else{
        return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
    }


}
Comments