//只有当是手机号的改变时才有操作
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField!=phoneTextField)
{
return YES;
}
NSString* numberString=[NSString stringWithFormat:@"%@%@", self.phoneTextField.text ,string];
if([string length]==0)
{
if([numberString length]>7)
{
numberString=[self.phoneTextField.text substringToIndex:[self.phoneTextField.text length]-1];
}
else
{
return YES;
}
}
NSString* phone=@"";
for(unsigned int i=0;i<[numberString length];i++)
{
char a=[numberString characterAtIndex:i];
NSString* b=[NSString stringWithFormat:@"%c", a];
BOOL result=[b compare:@"0"]==NSOrderedSame||[b compare:@"6"]==NSOrderedSame||
[b compare:@"2"]==NSOrderedSame||[b compare:@"7"]==NSOrderedSame||
[b compare:@"3"]==NSOrderedSame||[b compare:@"8"]==NSOrderedSame||
[b compare:@"4"]==NSOrderedSame||[b compare:@"9"]==NSOrderedSame||
[b compare:@"5"]==NSOrderedSame||[b compare:@"1"]==NSOrderedSame||
[b compare:@"+"]==NSOrderedSame||
[b compare:@"*"]==NSOrderedSame||[b compare:@"#"]==NSOrderedSame;
if(result)
{
phone=[NSString stringWithFormat:@"%@%@", phone ,b];
}
}
self.phoneTextField.text=[self encodePhoneNumber:phone];
return NO;
}
//编码手机号
-(NSString*) encodePhoneNumber:(NSString*) phone
{
NSLocale* locale = [NSLocale currentLocale];
if( [[locale localeIdentifier] compare:@"en_US"]!=NSOrderedSame )
return phone;
if( [phone length]==0 )
return phone;
if( [phone rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet] ].location==NSNotFound )
{
const char* string = [phone UTF8String];
int length = [phone lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
if ([[[[NSString alloc] initWithBytes:string length:1 encoding:NSASCIIStringEncoding] autorelease]intValue] == 1)
{
if( length > 11 )
return phone;
NSMutableData* array = [[[NSMutableData alloc] init] autorelease];
for( int i=0; i < length; i++ )
{
if( i==1 )
{
[array appendBytes:" (" length:2];
}
if( i == 4 )
{
[array appendBytes:") " length:2];
}
if( i==7 )
{
[array appendBytes:"-" length:1];
}
[array appendBytes:string++ length:1];
}
[array appendBytes:"\0" length:1];
NSString * value=[NSString stringWithUTF8String:[array bytes]];
if([value length]==4||[value length]==5||[value length]==6)
{
value=[value stringByAppendingString:@")"];
}
return value;
}
else
{
// (012) 345-6789
if( length > 10 )
return phone;
NSMutableData* array = [[[NSMutableData alloc] init] autorelease];
int i=0;
if( length <=7 )
{
for( i=0; i < length; i++ )
{
if( i==3 )
{
[array appendBytes:"-" length:1];
}
[array appendBytes:string++ length:1];
}
}
else
{
for( i=0; i < length; i++ )
{
if( i==0 )
[array appendBytes:"(" length:1];
if( i==3 )
[array appendBytes:") " length:2];
if( i==6 )
[array appendBytes:"-" length:1];
[array appendBytes:string++ length:1];
}
}
[array appendBytes:"\0" length:1];
NSString * value=[NSString stringWithUTF8String:(const char*)[array bytes]];
return value;
}
}
return phone;
}