仿滴滴验证码输入框,实现自动获取短信里的验证码【iOS,Object-C】

用六个UITextField控件实现了六位验证码输入框。
1.每个格子只能输入一个数字,输入完成后,光标会自动跳到下一个格子。
2.删除某个数字后,光标会跳到上一个格子。
3.收到短信验证码之后,键盘上方会出现验证码,点击之后,可以自动将验证码输入到输入框中。

步骤一 自定义UITextField
AuthCodeTextField.h文件
自定义TextField的目的是将textfield 的deleteBackward代理方法传递出来。

@class AuthCodeTextField;

@protocol AuthCodeDeleteDelegate <NSObject>

-(void)authCodeTextFieldDeleteBackward:(AuthCodeTextField *)textField;

@end

@interface AuthCodeTextField : UITextField

@property (nonatomic,weak) id <AuthCodeDeleteDelegate>auth_delegate;

@end

AuthCodeTextField.m文件
自定义的TextField,边框,圆角,都写在这里

@implementation AuthCodeTextField

-(instancetype)init{
    if(self = [super init]){
        self.keyboardType = UIKeyboardTypeNumberPad;
        self.textAlignment = NSTextAlignmentCenter;
        self.backgroundColor = RGB(236, 237, 246);
        self.layer.cornerRadius = 10;
        self.layer.masksToBounds = YES;
        self.textColor = [UIColor blackColor];
       // iOS12.0 系统之后,可以自动获取短信中的验证码
        if(@available(iOS 12.0,*)){
            self.textContentType = UITextContentTypeOneTimeCode;
        }
    }
    return self;
}
// 把这个代理方法传递出去
-(void)deleteBackward{
    if(self.text.length == 0){
        if([self.auth_delegate respondsToSelector:@selector(authCodeTextFieldDeleteBackward:)]){
            [self.auth_delegate authCodeTextFieldDeleteBackward:self];
        }
    }
    [super deleteBackward];
}

@end

AuthCodeInputView.h 文件
使用block的方式将 验证的结果传递出去

typedef void (^AuthCodeInputViewBlock)(BOOL success);

@interface AuthCodeInputView :UIView

-(instancetype)initWithFrame:(CGRect)frame andPhone:(NSString *)phone;

@property (nonatomic,copy) AuthCodeInputViewBlock authSuccess;

@end

AuthCodeInputView.m 文件

@interface AuthCodeInputView () <UITextFieldDelegate,AuthCodeDeleteDelegate>

@property (nonatomic,strong) NSString *phone;

@property (nonatomic,strong) UIView *backGround;

@property (nonatomic,strong) NSMutableArray *tfArr;

@property (nonatomic,strong) NSString *codeStr;

@end

@implementation AuthCodeInputView

-(instancetype)initWithFrame:(CGRect)frame andPhone:(NSString *)phone{
    if(self = [super initWithFrame:frame])
    {
        _phone = phone;
        [self createSubviews];
        [self sendSMSMessage];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(keyboardWillShow:)
                                                         name:UIKeyboardWillShowNotification
                                                       object:nil];
    }
    return self;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

// 发送短信验证码
-(void)sendSMSMessage
{
}

-(void)createSubviews
{
    _backGround = [[UIView alloc]init];
    _backGround.backgroundColor = [UIColor whiteColor];
    [self addSubview:_backGround];
    _backGround.layer.cornerRadius = 10;
    _backGround.layer.masksToBounds = YES;
    
    [_backGround mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(320);
        make.bottom.mas_equalTo(-400);
    }];
   
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [closeBtn setImage:[UIImage imageNamed:@"alert_close"] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(closeAuthCodeInputView) forControlEvents:UIControlEventTouchUpInside];
    [_backGround addSubview:closeBtn];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.top.mas_equalTo(10);
        make.width.height.mas_equalTo(40);
    }];
    
    UILabel *titleLab = [[UILabel alloc]init];
    titleLab.text = @"输入验证码";
    titleLab.textColor = [UIColor blackColor];
    titleLab.font = [UIFont systemFontOfSize:24];
    [_backGround addSubview:titleLab];
    [titleLab sizeToFit];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(35);
        make.top.mas_equalTo(32);
    }];
    
    NSString *phoneStr = @"";
    if(_phone.length > 7){
        phoneStr = [_phone stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }
    
    UILabel *textLab = [[UILabel alloc]init];
    textLab.text = [NSString stringWithFormat:@"为保障您的账号安全,需要进行短信验证码验证,我们将会发送验证码到%@,请输入验证码",phoneStr];
    textLab.textColor = RGBCOLOR(153, 153, 153);
    textLab.font = [UIFont systemFontOfSize:16];
    textLab.numberOfLines = 0;
    [_backGround addSubview:textLab];
    CGSize textLabSize = [textLab sizeThatFits:CGSizeMake(kMainScreenWidth-65, CGFLOAT_MAX)];
    [textLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(35);
        make.top.equalTo(titleLab.mas_bottom).offset(15);
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(textLabSize.height);
    }];
    
    self.tfArr = [NSMutableArray array];
    // 六个输入框
    CGFloat padding = 12;
    CGFloat width = 75/2;
    for (int i = 1 ; i < 7; i ++) {
        AuthCodeTextField *textF = [[AuthCodeTextField alloc]init];
        textF.tag = i;
        textF.auth_delegate = self;
        textF.delegate = self;
        [_backGround addSubview:textF];
        [self.tfArr addObject:textF];
        if(i == 1){
            [textF becomeFirstResponder];
        }
        CGFloat offset = 0;
        if(i <= 3){
            offset = -width*(3-i) - padding *(3-i) - padding/2 - width/2;
        }else{
            offset =  width*(i-4) + padding *(i-4) + padding/2 + width/2;
        }
        [textF mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(textLab.mas_bottom).offset(25);
            make.width.mas_equalTo(75/2);
            make.height.mas_equalTo(85/2);
            make.centerX.mas_equalTo(offset);
        }];
    }
     // 确认按钮
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [sureBtn setTitle:@"确认" forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(checkAuthcode) forControlEvents:UIControlEventTouchUpInside];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    sureBtn.backgroundColor = RGB(96, 138, 190);
    [_backGround addSubview:sureBtn];
    sureBtn.layer.cornerRadius = 45/2;
    sureBtn.layer.masksToBounds = YES;
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(75/2);
        make.right.mas_equalTo(-75/2);
        make.height.mas_equalTo(45);
        make.bottom.mas_equalTo(-32);
    }];
}

#pragma mark  UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// 获取短信中提取的验证码,自动输入到输入框中
    if(string.length > 1){
        for (int i = 0 ; i < self.tfArr.count; i++) {
            AuthCodeTextField *tf = self.tfArr[i];
            tf.text = [string substringWithRange:NSMakeRange(i, 1)];
        }
        return NO;
    }
    NSInteger nextTag = textField.tag + 1;
    UITextField *nextTextField = [self viewWithTag:nextTag];
    if(string.length > 0){
        textField.text = string;
        if (nextTextField) {
            [nextTextField becomeFirstResponder];
        }
        else
        {
            self.codeStr = @"";
            for (AuthCodeTextField *tf in self.tfArr) {
                self.codeStr = [self.codeStr stringByAppendingString:tf.text];
            }
        }
        return NO;
    }
    else
    {
        return YES;
    }
}
// 调用接口验证验证码正确性
-(void)checkAuthcode
{
    if(self.codeStr.length < 6){
      //验证码不足六位
        return;
    }
}

-(void)closeAuthCodeInputView{
    [self removeFromSuperview];
}

#pragma mark  AuthCodeDeleteDelegate 删除输入的值
-(void)authCodeTextFieldDeleteBackward:(AuthCodeTextField *)textField
{   self.codeStr = @"";
    NSInteger lastTag = textField.tag - 1;
    AuthCodeTextField *lastTextField = [self viewWithTag:lastTag];
    [lastTextField becomeFirstResponder];
}

#pragma mark  NSNotificationCenter
-(void)keyboardWillShow:(NSNotification *)notify
{
    NSDictionary *userInfo = [notify userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    //height 就是键盘的高度
    int height = keyboardRect.size.height;
    [_backGround mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(320);
        make.bottom.mas_equalTo(-height+10);
    }];
}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,723评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,485评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,998评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,323评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,355评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,079评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,389评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,019评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,519评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,971评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,100评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,738评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,293评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,289评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,517评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,547评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,834评论 2 345

推荐阅读更多精彩内容