Allowing single digit in UITextField in iOS

前端 未结 13 1277
耶瑟儿~
耶瑟儿~ 2020-12-05 03:55

I have a Verification ViewController, I get 4 digit verification code by SMS and I need to enter those code to login, I have created the ViewController

相关标签:
13条回答
  • 2020-12-05 04:18

    I have taken one Hidden text field & four imageViews for that with two images. One for Blank and other for Bullet same as iOS default.

    Also set tags for four imageviews.

    On Load set Focus for Pin Code

    - (void)startPinCode
    {
        txtPinCodeLockDigits.text = @"";
    
        for (int i = 1; i <= 4; i++) {
    
           UIImageView *img = (UIImageView *)[self.view viewWithTag:i];
           [img setImage:[UIImage imageNamed:@"Img_BG_PinCode.png"]];
        }
    
        [txtPinCodeLockDigits becomeFirstResponder];
    }
    

    Then change imageview's images as per user input and only allow four characters

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        NSString *result = [textField.text stringByReplacingCharactersInRange:range withString:string];
        textField.text = result;
    
        for (int i = 1; i <= 4; i++) {
    
           UIImageView *img = (UIImageView *)[self.view viewWithTag:i];
           if (i <= [result length])
               [img setImage:[UIImage imageNamed:@"Img_BG_PinCode_Filled.png"]];
           else
               [img setImage:[UIImage imageNamed:@"Img_BG_PinCode.png"]];
         }
    
         NSLog(@"Result :: %@", result);
    
         if ([result length] == 4) {
            [self performSelector:@selector(keyGenerationForApplication:) withObject:result afterDelay:0.2];
         }
    
         return NO;
    }
    

    After Four characters call function for generated PIN Code and store it in User Defaults same as iOS default PIN settings

    - (void)keyGenerationForApplication:(NSString *)pinCode
    {
         int appCode = [pinCode intValue];
         [DefaultsValues setIntegerValueToUserDefaults:appCode ForKey:PIN_LOCK_PATTERN];
    }
    

    Here, you can again call StartPinCode method for re-confirming code.

    Hopefully, it'll help you.
    Thanks

    0 讨论(0)
提交回复
热议问题