干得好。不过,我会将其归为 NSString 的一个类别。
- (NSString*)deleteCharacterAtPosition:(int)position inString:(NSString*)myString {
NSMutableString *mutableString = [myString mutableCopy];
[mutableString deleteCharactersInRange:NSMakeRange(position, 1)];
return mutableString;
}
如果您不想删除任何数字。然后,您应该在调用此函数之前检查该位置是否有非数字字符。
或者你可以这样做:
- (NSString*)deleteCharacterAtPosition:(int)position inString:(NSString*)myString {
NSRange range;
range.location = position;
range.length = 1;
return [test stringByReplacingCharactersInRange:range withString:@""];
}
这是检查位置是否为数字的方法:
- (bool)isCharacterAtPositionADigit:(int)position inString:(NSString*)myString {
unichar c = [myString characterAtIndex:position];
NSCharacterSet *numericSet = [NSCharacterSet decimalDigitCharacterSet];
if ([numericSet characterIsMember:c]) {
return true;
}
return false;
}
现在这就是你想要的:
- (IBAction)clearTextKeyPressed:(id)sender {
NSString *enteredText = [NSString stringWithFormat:@"%@", self.targetTextField.text];
int positionToDelete = 3;
if ( [enteredText length] > 0 && [enteredText length] >= positionToDelete) {
if (![self isCharacterAtPositionADigit:positionToDelete inString:enteredText])
return;
NSString* finalText = [self deleteCharacterAtPosition:positionToDelete inString:enteredText];
self.targetTextField.text = finalText;
[self.numericGridKeypadDelegate textFieldDidChange:self.targetTextField];
}
}