我的 iphone 上有一个表单屏幕,我正在尝试复制 Iphone 联系人应用程序,它将自动完成以下电话号码格式:(233)323-2323。
我非常接近我能够在文本字段中看到格式更新,但其他 4 个文本字段现在不起作用。我无法编辑它们。我将其缩小到 shouldchangecharactersinrange 函数。
请看下面的代码。
谢谢。
quick look at the method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(([textField tag] == 2)){
int length = [self getLength:textField.text];
//NSLog(@"Length = %d ",length);
if(length == 10)
{
if(range.length == 0)
return NO;
}
if(length == 3)
{
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 == 6)
{
NSString *num = [self formatNumber:textField.text];
//NSLog(@"%@",[num substringToIndex:3]);
//NSLog(@"%@",[num substringFromIndex:3]);
textField.text = [NSString stringWithFormat:@"(%@) %@-",[num substringToIndex:3],[num substringFromIndex:3]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:@"(%@) %@",[num substringToIndex:3],[num substringFromIndex:3]];
}
return YES;
}else if([textField tag] != 1){
return NO;
}
}
-(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;
}
Firstcontroller.h
@interface FirstTVContoller : UIViewController <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UIPickerViewDataSource,UIPickerViewDelegate>{
NSMutableArray *items;
NSMutableArray *titles;
NSMutableArray *section2items;
NSMutableArray *dataArray;
UITableView *table;
contactTitle *title;
//launch title picker
UIPickerView *titlePicker;
UILabel *titleLabel;
UITextField *titleField;
UIActionSheet *actionSheet;
UIPickerView *pickerView;
UITextField *textField;
UITextField *FirstnameTextfield;
UITextField *LastnameTextfield;
UITextField *CompanyTextfield;
UITextField *phoneTextfield;
//the scrollview
UIScrollView *scrollview;
}
//attributes for title picker
@property (strong, nonatomic) NSArray * titlecategories;
@property (strong, nonatomic) NSArray * titleidSlot;
@end
FirstTVController.m
//
// FirstTVContoller.m
// TwoTableViews
@implementation FirstTVContoller
@synthesize titleidSlot;
@synthesize titlecategories;
- (BOOL) connectedToNetwork
{
// Create zero addy
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags)
{
//NSLog(@"Error. Could not recover network reachability flags");
return NO;
}
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
NSURL *testURL = [NSURL URLWithString:SERVERNAME];
NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self];
return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;
}
-(void)viewDidLoad{
[super viewDidLoad];
// scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 300, 500)];
// scrollview.pagingEnabled = YES;
//
// //[scrollview addSubview:self.view];
// [self.view addSubview:scrollview];
table.scrollEnabled = YES;
dataArray = [[NSMutableArray alloc] init];
titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 290, 30)];
//dropper
titleField = [[UITextField alloc] initWithFrame:CGRectMake(10, 2, 300, 30)];
titleField.layer.cornerRadius = 8;
titleField.backgroundColor = [UIColor clearColor];
NSArray *firstItemsArray = [[NSArray alloc] initWithObjects:@"1",@"2", nil];
NSDictionary *firstItemsArrayDict = [NSDictionary dictionaryWithObject:firstItemsArray forKey:@"data"];
[dataArray addObject:firstItemsArrayDict];
//Second section dat
NSArray *secondItemsArray = [[NSArray alloc] initWithObjects:@"1", nil];
NSDictionary *secondItemsArrayDict = [NSDictionary dictionaryWithObject:secondItemsArray forKey:@"data"];
[dataArray addObject:secondItemsArrayDict];
NSArray *thirdItemsArray = [[NSArray alloc] initWithObjects:@"1",@"2",@"3", nil];
NSDictionary *thirdItemsArrayDict = [NSDictionary dictionaryWithObject:thirdItemsArray forKey:@"data"];
[dataArray addObject:thirdItemsArrayDict];
NSLog(@"the dataArray%@",dataArray);
if([self connectedToNetwork]){
dispatch_async(kBgQueue, ^{
//build the url of strings
FULLURL = [SERVERNAME stringByAppendingFormat:ushTitleLink];
//create the url
NSURL *url = [[NSURL alloc] initWithString:FULLURL];
//NSLog(@"here title url%@",url);
//get the data from the url
NSData* data = [NSData dataWithContentsOfURL: url];
NSLog(@"here%@",data);
//get the data from the url
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
NSLog(@"titleid:%@",TITLEID);
NSLog(@"title categories:%@",titlecategories);
});
[table setBounces:NO];
}else{
dispatch_async(dispatch_get_main_queue(), ^ {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: @"Please Check your internet connection"
message:@"Enable your internet connection"
delegate: nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
});
}
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return [dataArray count];
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
//Number of rows it should expect should be based on the section
NSDictionary *dictionary = [dataArray objectAtIndex:section];
NSArray *array = [dictionary objectForKey:@"data"];
return [array count];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section == 1){
cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"longdropper300.png"]];
}
else{
cell.backgroundColor = [UIColor whiteColor];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
textField = [[UITextField alloc] initWithFrame:CGRectMake(15, 10, 290, 30)];
static NSString *cellValue = @"Cell";
UITableViewCell *cell =nil;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellValue];
}
cell.selectionStyle = UITableViewCellSelectionStyleGray;
if ([indexPath section] == 0) {
//cellValue=[items objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle= UITableViewCellSelectionStyleNone;
//textField.tag = 1;
textField.adjustsFontSizeToFitWidth = YES;
textField.textColor = [UIColor blackColor];
if(indexPath.section == 0){
//textfield for email
if ([indexPath row] == 0) {
textField.tag = 1;
textField.text = EMAIL;
textField.textColor= [UIColor blackColor];
textField.placeholder = @"Email: example@gmail.com";
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.returnKeyType = UIReturnKeyNext;
}
//textfield for phone number
else {
textField.tag = 2;
if ([PHONENUMBER isEqual: [NSNull null]] && PHONENUMBER == nil && PHONENUMBER == NULL && [PHONENUMBER isEqual: @""]){
NSLog(@"phone is empty%@",PHONENUMBER);
//[PHONENUMBER isEqual:@"frank"];
}else{
NSLog(@"phone is not empty%@",PHONENUMBER);
textField.text = PHONENUMBER;
}
textField.placeholder = @"Phone: (xxx)xxx-xxxx";
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDefault;
textField.secureTextEntry = NO;
}
textField.backgroundColor = [UIColor whiteColor];
//textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
//textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
textField.textAlignment = UITextAlignmentLeft;
//textField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[textField setEnabled: YES];
textField.delegate = self;
[cell addSubview:textField];
}
}
if(indexPath.section == 1){
[titleField setTextColor:[UIColor whiteColor]];
titleField.tag = 3;
titleField.placeholder = @"Select Contact Title";
titleField.returnKeyType = UIReturnKeyNext;
//titleField == textField.tag = 3;
if ([TITLENAME isEqual: [NSNull null]]){
NSLog(@"titlename is empty%@",TITLENAME);
}else{
NSLog(@"titlename is not empty%@",TITLENAME);
titleField.text = TITLENAME;
}
titleField.keyboardType = UIKeyboardTypeDefault;
titleField.returnKeyType = UIReturnKeyDone;
titleField.secureTextEntry = NO;
titleField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
titleField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
titleField.textAlignment = UITextAlignmentCenter;
titleField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[titleField setEnabled: NO];
titleField.delegate = self;
[cell addSubview:titleField];
NSLog(@"here is the titlename%@",TITLENAME);
}
if(indexPath.section == 2){
if ([indexPath row] == 0) {
textField.tag = 4;
textField.placeholder = @"First Name";
cell.selectionStyle= UITableViewCellSelectionStyleNone;
if ([FIRSTNAME isEqual: [NSNull null]]){
NSLog(@"firstname is empty%@",FIRSTNAME);
textField.text = @"";
}else{
textField.text = FIRSTNAME;
}
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.returnKeyType = UIReturnKeyNext;
}
if([indexPath row] == 1){
textField.tag = 5;
textField.placeholder = @"Last Name";
if ([LASTNAME isEqual: [NSNull null]]){
NSLog(@"lastname is empty%@",LASTNAME);
textField.text = @"";
}else{
textField.text = LASTNAME;
}
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyNext;
//textField.secureTextEntry = NO;
}
if([indexPath row] == 2){
textField.tag = 6;
textField.placeholder = @"Company";
if ([COMPANY isEqual: [NSNull null]]){
NSLog(@"company is empty%@",COMPANY);
textField.text = @"";
}
else{
textField.text = COMPANY;
}
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.secureTextEntry = NO;
}
//]textField.backgroundColor = [UIColor whiteColor];
textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
textField.textAlignment = UITextAlignmentLeft;
textField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[textField setEnabled: YES];
textField.delegate = self;
[cell addSubview:textField];
}
return cell;
}
//Change the Height of title cell drop down
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
if (indexPath.section == 1) {
if (indexPath.row == 0) {
return 30;
}
}
return 45;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
if(([textField tag] == 1)){
NSString *emailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
//Valid email address
if ([emailTest evaluateWithObject:textField.text] == YES)
{
EMAIL = [textField.text copy];
NSLog(@"here is the email%@",EMAIL);
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: @"Bad Email"
message: @"Please Re-enter the email address with a valid email"
delegate: nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
textField.text = nil;
NSLog(@"email not in proper format");
}
}
if(([textField tag] == 2)){
//NSString *phoneRegex = @"[235689][0-9]{6}([0-9]{3})?";
//NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
//valid email address
//if ([phoneTest evaluateWithObject:textField.text] == YES)
// {
//if(PHONENUMBER != nil){
NSString *tempString = [textField.text copy];
NSString *unformatted = tempString;
NSLog(@"unformatted phonenumber%@",unformatted);
NSArray *stringComponents = [NSArray arrayWithObjects:[unformatted substringWithRange:NSMakeRange(0, 3)],
[unformatted substringWithRange:NSMakeRange(3, 3)],
[unformatted substringWithRange:NSMakeRange(6, [unformatted length]-6)], nil];
NSString *formattedString = [NSString stringWithFormat:@"(%@)%@-%@", [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1], [stringComponents objectAtIndex:2]];
NSLog(@"Formatted Phone Number: %@", formattedString);
PHONENUMBER = formattedString;
NSLog(@"here is the phone number %@",PHONENUMBER);
// }
// else
// {
// NSLog(@"Phone Number Invalid");
// UIAlertView *alert = [[UIAlertView alloc]
// initWithTitle: @"xxx-xxx-xxxx"
// message: @"Please enter a valid phone number"
// delegate: nil
// cancelButtonTitle:@"OK"
// otherButtonTitles:nil];
// [alert show];
// textField.text = nil;
// }
}
if(([textField tag] == 4)){
FIRSTNAME = [textField.text copy];
NSLog(@"here is the firstName%@",FIRSTNAME);
}
if(([textField tag] == 5)){
LASTNAME = [textField.text copy];
NSLog(@"here is the Last Name%@",LASTNAME);
}
if(([textField tag] == 6)){
COMPANY = [textField.text copy];
NSLog(@"here is the Company%@",COMPANY);
}
return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
title = [[contactTitle alloc] initWithDictionary:json];
//NSLog(@"here is the dictionary from json: %@", json);
NSLog(@"here is title that was the json %@", title);
NSLog(@"here is the title from json: %@", title.cTitle);
NSLog(@"here is the title id from json %@", title.cTitleID);
}
//PickerViewController.m
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
dispatch_queue_t downloadQueue = dispatch_queue_create("data loader", NULL);
dispatch_async(downloadQueue, ^{
TITLENAME = [title.cTitle objectAtIndex:row], row;
//NSLog(@"here is the selected title%@", TITLENAME);
TITLEID = [title.cTitleID objectAtIndex:row], row;
//NSLog(@"here is the selected title%@", TITLEID);
});
//thePickerView.hidden = YES;
}
//PickerView
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
return [title.cTitle count];
}
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [title.cTitle
objectAtIndex:row];
}
- (void)fetchedContactIDData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSLog(@"here is the login info from json: %@", json);
// NSString *FALSELOGIN;
CONTACTID = [json valueForKey:@"contactid"];
NSLog(@"CONTACT ID: %@", CONTACTID);
// LOGINID = [json valueForKey:@"login"];
// NSLog(@"LOGIN ID: %@", LOGINID);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//get the country selected
//NSString *selectedCell = nil;
if(indexPath.section == 1){
titleField.text = @"Select Contact Title";
NSLog(@"you selected:%@",TITLENAME);
actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:nil
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;
[actionSheet addSubview:pickerView];
UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Cancel"]];
closeButton.momentary = YES;
closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
closeButton.tintColor = [UIColor blackColor];
[closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
[actionSheet addSubview:closeButton];
//[actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[actionSheet showInView:self.view];
[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}else{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(([textField tag] == 2)){
int length = [self getLength:textField.text];
//NSLog(@"Length = %d ",length);
if(length == 10)
{
if(range.length == 0)
return NO;
}
if(length == 3)
{
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 == 6)
{
NSString *num = [self formatNumber:textField.text];
//NSLog(@"%@",[num substringToIndex:3]);
//NSLog(@"%@",[num substringFromIndex:3]);
textField.text = [NSString stringWithFormat:@"(%@) %@-",[num substringToIndex:3],[num substringFromIndex:3]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:@"(%@) %@",[num substringToIndex:3],[num substringFromIndex:3]];
}
return YES;
}else if([textField tag] != 1){
return NO;
}
}
-(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;
}
- (void)dismissActionSheet:(id)sender{
[actionSheet dismissWithClickedButtonIndex:0 animated:YES];
//pickerButton.titleLabel.text = TITLENAME;
//titleLabel.text= TITLENAME;
titleField.text = TITLENAME;
[titleLabel reloadInputViews];
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
[titlePicker removeConstraints:titlePicker];
[titlePicker removeFromSuperview];
}
@end