Regex电话号码方法破坏文本字段



当我的代码中有我的方法formatPhoneNumber/textField方法时,它不允许我键入任何其他字段。当我删除它们时,问题就消失了。有人能告诉我导致这个问题的代码出了什么问题吗?

//-------------------------------------------------------------------------------------------------------------------------------------------------
@interface RegisterView()
@property (strong, nonatomic) IBOutlet UITableViewCell *cellName;
@property (strong, nonatomic) IBOutlet UITableViewCell *cellEmail;
@property (strong, nonatomic) IBOutlet UITableViewCell *cellPassword;
@property (strong, nonatomic) IBOutlet UITableViewCell *cellButton;
@property (strong, nonatomic) IBOutlet UITableViewCell *cellPhone;
@property (strong, nonatomic) IBOutlet UITableViewCell *cellFName;
@property (strong, nonatomic) IBOutlet UITableViewCell *cellLName;
@property (strong, nonatomic) IBOutlet UITextField     *fieldName;
@property (strong, nonatomic) IBOutlet UITextField     *fieldEmail;
@property (strong, nonatomic) IBOutlet UITextField     *fieldPassword;
@property (strong, nonatomic) IBOutlet UITextField     *fieldPhone;
@property (strong, nonatomic) IBOutlet UITextField     *fieldFName;
@property (strong, nonatomic) IBOutlet UITextField     *fieldLName;
@end
//-------------------------------------------------------------------------------------------------------------------------------------------------
@implementation RegisterView
@synthesize cellName,  cellEmail,  cellPassword,  cellButton, cellPhone, cellLName, cellFName;
@synthesize fieldName, fieldEmail, fieldPassword, fieldPhone, fieldLName,fieldFName;
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)viewDidLoad
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    [super viewDidLoad];
    self.title = @"Register";
    //UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"giberWallpaper.png"]];
    //self.tableView.backgroundColor = background;
    self.navigationController.navigationBar.tintColor= [UIColor colorWithRed:(255/256.0) green:(128/256.0) blue:(0/256.0) alpha:(1.0)];
    //---------------------------------------------------------------------------------------------------------------------------------------------
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.tableView addGestureRecognizer:gestureRecognizer];
    gestureRecognizer.cancelsTouchesInView = NO;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)viewDidAppear:(BOOL)animated
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    [super viewDidAppear:animated];
    [fieldName becomeFirstResponder];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)dismissKeyboard
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    [self.view endEditing:YES];
}
#pragma mark - User actions
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)actionRegister
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    NSString *name       = fieldName.text;
    NSString *email      = [fieldEmail.text lowercaseString];
    NSString *password   = fieldPassword.text;
    NSString *phoneNumber= fieldPhone.text;
    NSString *fName      = fieldFName.text;
    NSString *lName      = fieldLName.text;
    NSString *fullName   = [NSString stringWithFormat: @"%@ %@", fName, lName];
    //---------------------------------------------------------------------------------------------------------------------------------------------
    if ([name length] < 3)          { [ProgressHUD showError:@"Name is too short."]; return; }
    if ([email length] == 0)        { [ProgressHUD showError:@"Email must be set."]; return; }
    if ([password length] == 0)     { [ProgressHUD showError:@"Password must be set."]; return; }
    if ([phoneNumber length] == 0)  { [ProgressHUD showError:@"Phone number must be set."]; return; }
    if ([lName length] < 2)         { [ProgressHUD showError:@"Name is too short."]; return; }
    if ([fName length] < 2)         { [ProgressHUD showError:@"Name is too short."]; return; }
    //---------------------------------------------------------------------------------------------------------------------------------------------
    [ProgressHUD show:@"Please wait..." Interaction:NO];
    //---------------------------------------------------------------------------------------------------------------------------------------------
    PFUser *user = [PFUser user];
    user.email = email;
    user.username = email;
    user.password = password;
    int randInt = arc4random() % 9000 + 1000;
    NSString *strInt = [NSString stringWithFormat:@"%d",randInt];
    user[PF_USER_PIN]            = strInt;
    user[PF_USER_NICKNAME]       = name;
    user[PF_USER_FIRSTNAME]      = fName;
    user[PF_USER_LASTNAME]       = lName;
    user[PF_USER_PHONENUMBER]    = phoneNumber;
    user[PF_USER_EMAILCOPY]      = email;
    user[PF_USER_FULLNAME]       = fullName;
    user[PF_USER_FULLNAME_LOWER] = [fullName lowercaseString];
    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
    {
        if (error == nil)
        {
            ParsePushUserAssign();
            PostNotification(NOTIFICATION_USER_LOGGED_IN);
            [ProgressHUD showSuccess:@"Succeed."];
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        else [ProgressHUD showError:error.userInfo[@"error"]];
    }];
}
-(NSString*) formatPhoneNumber:(NSString*) simpleNumber deleteLastChar:(BOOL)deleteLastChar {
    if(simpleNumber.length==0) return @"";
    // use regex to remove non-digits(including spaces) so we are left with just the numbers
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[\s-\(\)]" options:NSRegularExpressionCaseInsensitive error:&error];
    simpleNumber = [regex stringByReplacingMatchesInString:simpleNumber options:0 range:NSMakeRange(0, [simpleNumber length]) withTemplate:@""];
    // check if the number is to long
    if(simpleNumber.length>10) {
        // remove last extra chars.
        simpleNumber = [simpleNumber substringToIndex:10];
    }
    if(deleteLastChar) {
        // should we delete the last digit?
        simpleNumber = [simpleNumber substringToIndex:[simpleNumber length] - 1];
    }
    // 123 456 7890
    // format the number.. if it's less then 7 digits.. then use this regex.
    if(simpleNumber.length<7)
        simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:@"(\d{3})(\d+)"
                                                               withString:@"($1) $2"
                                                                  options:NSRegularExpressionSearch
                                                                    range:NSMakeRange(0, [simpleNumber length])];
    else   // else do this one..
        simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:@"(\d{3})(\d{3})(\d+)"
                                                               withString:@"($1) $2-$3"
                                                                  options:NSRegularExpressionSearch
                                                                    range:NSMakeRange(0, [simpleNumber length])];
    return simpleNumber;
}
- (BOOL)textField:(UITextField *)fieldPhone shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString* totalString = [NSString stringWithFormat:@"%@%@",self.fieldPhone.text,string];
    // if it's the phone number textfield format it.
    if(self.fieldPhone.tag==102 ) {
        if (range.length == 1) {
            // Delete button was hit.. so tell the method to delete the last char.
            self.fieldPhone.text = [self formatPhoneNumber:totalString deleteLastChar:YES];
        } else {
            self.fieldPhone.text = [self formatPhoneNumber:totalString deleteLastChar:NO ];
        }
        return false;
    }
    return YES; 
}
#pragma mark - Table view data source
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    return 1;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    return 7;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    if (indexPath.row == 0) return cellName;
    if (indexPath.row == 1) return cellFName;
    if (indexPath.row == 2) return cellLName;
    if (indexPath.row == 3) return cellPhone;
    if (indexPath.row == 4) return cellEmail;
    if (indexPath.row == 5) return cellPassword;
    if (indexPath.row == 6) return cellButton;
    return nil;
}
#pragma mark - Table view delegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //---------------------------------------------------------------------------------------------------------------------------------------------
    if (indexPath.row == 6) [self actionRegister];
}
#pragma mark - UITextField delegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (BOOL)textFieldShouldReturn:(UITextField *)textField
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    if (textField == fieldName)
    {
        [fieldFName becomeFirstResponder];
    }
    if (textField == fieldFName)
    {
        [fieldLName becomeFirstResponder];
    }
    if (textField == fieldLName)
    {
        [fieldPhone becomeFirstResponder];
    }
    if (textField == fieldPhone)
    {
        [fieldEmail becomeFirstResponder];
    }
    if (textField == fieldEmail)
    {
        [fieldPassword becomeFirstResponder];
    }
    if (textField == fieldPassword)
    {
        [self actionRegister];
    }
    return YES;
}
@end

shouldChangeCharactersInRange:方法中将fieldPhone更改为textField,这与UITextField fieldPhone的本地声明冲突。

您还需要将该方法中的所有引用更新为新的textField。因此,您的新方法将如下所示:- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

最新更新