1
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
int length = [self getLength:textField.text];
//NSLog(@"Length = %d ",length);
if(length == 11)
{
if(range.length == 0)
return NO;
}
if(length == 2)
{
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:@"(%@)",num];
if(range.length > 0)
textField.text = [NSString stringWithFormat:@"%@",[num substringToIndex:3]];
}
else if(length == 7)
{
NSString *num = [self formatNumber:textField.text];
//NSLog(@"%@",[num substringToIndex:3]);
//NSLog(@"%@",[num substringFromIndex:3]);
textField.text = [NSString stringWithFormat:@"(%@) %@-",[num substringToIndex:2],[num substringFromIndex:2]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:@"(%@) %@",[num substringToIndex:2],[num substringFromIndex:2]];
}
return YES;
}
-(NSString*)formatNumber:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
NSLog(@"%@", mobileNumber);
int length = [mobileNumber length];
if(length > 10)
{
mobileNumber = [mobileNumber substringFromIndex: length-10];
NSLog(@"%@", mobileNumber);
}
return mobileNumber;
}
-(int)getLength:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
int length = [mobileNumber length];
return length;
}
Please explain your problem with the current code better. Only the title and a copy/code copy make the question extremely poor. Check out the guides [Ask] and [about]. And welcome to SOPT :)
– brasofilo