iOS 写一个验证码输入框

前言:

这次要做一个验证码输入框,要求:
1、验证码数字之间是分割开的,有自己的样式。
2、验证码输入框要能够接收来自键盘顶部短信的快捷输入。

前后换了两套思路,终于是把这个玩意写完了,这次的代码也挺烦人的,真的烦。

效果图:

获取验证码.gif
获取验证码2.gif

代码思路:
1、先弄个一个父容器 UIView A
2、在A上放置一个输入框 UITextField
3、在A上放置一个UIView B,这个B,要把用户交互关闭掉,这样点击A的时候,B不响应点击,UITextField 就变成了响应者
4、在B上放置 4 个验证码格子,这个格子是自定义的UIView C, 这个C关闭用户交互,在这个C上放置UILabel用于显示数字,放置光标和下划线。
5、在你点击输入的时候,其实响应你输入的是 UITextField 然后通过使用通知 UITextFieldTextDidChangeNotification 来截获输入的内容,把这些内容,显示到自定的 C 上,从而达到效果

思路图:


层叠.png

因为我这个输入框,要求有光标闪动,要求从键盘短信直接输入验证码,所以才有这样的代码。

代码地址:

代码地址:https://github.com/gityuency/ObjectiveCTools
示例代码类名 【SMSCodeInputView】【SMSCodeView】

上代码!

SMSCodeInputView.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface SMSCodeInputView : UIView

///验证码文字
@property (strong, nonatomic) NSString *codeText;

///设置验证码位数 默认 4 位
@property (nonatomic) NSInteger codeCount;

///验证码数字之间的间距 默认 35
@property (nonatomic) CGFloat codeSpace;

@end

NS_ASSUME_NONNULL_END

SMSCodeInputView.m

#import "SMSCodeInputView.h"
#import "SMSCodeView.h"

@interface SMSCodeInputView () <UITextFieldDelegate>
///输入框
@property (strong, nonatomic) UITextField *textField;
///格子数组
@property (nonatomic,strong) NSMutableArray <SMSCodeView *> *arrayTextFidld;
///记录上一次的字符串
@property (strong, nonatomic) NSString *lastString;
///放置小格子
@property (strong, nonatomic) UIView *contentView;

@end

@implementation SMSCodeInputView

- (instancetype)init {
    if (self = [super init]) {
        [self config];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self config];
    }
    return self;
}

- (void)config {
    
    _codeCount = 4;  //在初始化函数里面, 如果重写了某个属性的setter方法, 那么使用 self.codeCount 会直接调用重写的 setter 方法, 会造成惊喜!
    _codeSpace = 35;
    
    //初始化数组
    _arrayTextFidld = [NSMutableArray array];
    
    _lastString = @"";
    
    self.backgroundColor = UIColor.blackColor;
    
    //输入框
    _textField = [[UITextField alloc] init];
    _textField.backgroundColor = [UIColor purpleColor];
    _textField.keyboardType = UIKeyboardTypeNumberPad;
    _textField.delegate = self;
    [self addSubview:_textField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeValue:) name:UITextFieldTextDidChangeNotification object:_textField];
    
    //放置View
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = UIColor.whiteColor;
    _contentView.userInteractionEnabled = NO;
    [self addSubview:_contentView];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    [self updateSubViews];
}

- (void)updateSubViews {
    
    self.textField.frame = self.bounds;
    self.contentView.frame = self.bounds;
    
    /*
     方案1: 直接把原来的都删掉, 重新创建
     for (SMSCodeView *v in [self.arrayTextFidld reverseObjectEnumerator]) {
     [v removeFromSuperview];
     [self.arrayTextFidld removeObject:v];
     }
     */
    
    //方案2:能用就用,少了再建
    if (_arrayTextFidld.count < _codeCount) { //已经存在的子控件比新来的数要小, 那么就创建
        NSUInteger c = _codeCount - _arrayTextFidld.count;
        for (NSInteger i = 0; i < c; i ++) {
            SMSCodeView *v = [[SMSCodeView alloc] init];
            [_arrayTextFidld addObject:v];
        }
    } else if (_arrayTextFidld.count == _codeCount) { //个数相等
        
        return; //如果return,那么就是什么都不做, 如果不return, 那么后续可以更新颜色之类, 或者在转屏的时候重新布局
        
    } else if (_arrayTextFidld.count > _codeCount) { //个数有多余, 那么不用创建新的, 为了尽可能释放内存, 把不用的移除掉,
        NSUInteger c = _arrayTextFidld.count - _codeCount;
        for (NSInteger i = 0; i < c; i ++) {
            [_arrayTextFidld.lastObject removeFromSuperview];
            [_arrayTextFidld removeLastObject];
        }
    }
    
    //可用宽度 / 格子总数
    CGFloat w = (self.bounds.size.width - _codeSpace * (_codeCount - 1)) / (_codeCount * 1.0);
    
    //重新布局小格子
    for (NSInteger i = 0; i < _arrayTextFidld.count; i ++) {
        SMSCodeView *t = _arrayTextFidld[i];
        [self.contentView addSubview:t];
        t.frame = CGRectMake(i * (w + _codeSpace), 0, w, self.bounds.size.height);
    }
}

//已经编辑
- (void)textFieldDidChangeValue:(NSNotification *)notification {
    
    UITextField *sender = (UITextField *)[notification object];
    
    /*
     bug: NSUInteger.
     sender.text.length 返回值是 NSUInteger,无符号整型, 当两个无符号整型做减法, 如果 6 - 9, 那么不会得到 -3, 而是一串很长的整型数, 也就是计算失误
     */
    
    BOOL a = sender.text.length >= self.lastString.length;
    BOOL b = sender.text.length - self.lastString.length >= _codeCount;
    if (a && b) { //判断为一连串验证码输入, 那么,最后N个,就是来自键盘上的短信验证码,取最后N个
        NSLog(@"一连串的输入");
        sender.text = [sender.text substringFromIndex:sender.text.length - _codeCount];
    }
    
    if (sender.text.length >= _codeCount + 1) { //对于持续输入,只要前面N个就行
        NSLog(@"持续输入");
        sender.text = [sender.text substringToIndex:_codeCount - 1];
    }
    
    //字符串转数组
    NSMutableArray <NSString *> *stringArray = [NSMutableArray array];
    NSString *temp = nil;
    for(int i = 0; i < [sender.text length]; i++) {
        temp = [sender.text substringWithRange:NSMakeRange(i,1)];
        [stringArray addObject:temp];
    }
    
    //设置文字
    for(int i = 0; i < self.arrayTextFidld.count; i++) {
        SMSCodeView *SMSCodeView = self.arrayTextFidld[i];
        if (i < stringArray.count) {
            SMSCodeView.text = stringArray[i];
        } else {
            SMSCodeView.text = @"";
        }
    }
    
    //设置光标
    if (stringArray.count == 0) {
        for(int i = 0; i < self.arrayTextFidld.count; i++) {
            BOOL hide = (i == 0 ? YES : NO);
            SMSCodeView *SMSCodeView = self.arrayTextFidld[i];
            SMSCodeView.showCursor = hide;
        }
    } else if (stringArray.count == self.arrayTextFidld.count) {
        for(int i = 0; i < self.arrayTextFidld.count; i++) {
            SMSCodeView *SMSCodeView = self.arrayTextFidld[i];
            SMSCodeView.showCursor = NO;
        }
    } else {
        for(int i = 0; i < self.arrayTextFidld.count; i++) {
            SMSCodeView *SMSCodeView = self.arrayTextFidld[i];
            if (i == stringArray.count - 1) {
                SMSCodeView.showCursor = YES;
            } else {
                SMSCodeView.showCursor = NO;
            }
        }
    }
    
    if (stringArray.count == self.arrayTextFidld.count) {
        [self.textField resignFirstResponder];
    }
    
    self.lastString = sender.text;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    //检查上一次的字符串
    if (self.lastString.length == 0 || self.lastString.length == 1) {
        self.arrayTextFidld.firstObject.showCursor = YES;
    } else if (self.lastString.length == self.arrayTextFidld.count) {
        self.arrayTextFidld.lastObject.showCursor = YES;
    } else {
        self.arrayTextFidld[self.lastString.length - 1].showCursor = YES;
    }
}

- (NSString *)codeText {
    return self.textField.text;
}

- (BOOL)resignFirstResponder {
    for(int i = 0; i < self.arrayTextFidld.count; i++) {
        SMSCodeView *SMSCodeView = self.arrayTextFidld[i];
        SMSCodeView.showCursor = NO;
    }
    [self.textField resignFirstResponder];
    return YES;
}

- (BOOL)becomeFirstResponder {
    [self.textField becomeFirstResponder];
    return YES;
}

///如果要求可以随时更改输入位数, 那么,
- (void)setCodeCount:(NSInteger)codeCount {
    _codeCount = codeCount;
    
    //因为个数改变,清空之前输入的内容
    self.lastString = @"";
    self.textField.text = @"";
    
    for (NSInteger i = 0; i < _arrayTextFidld.count; i ++) {
        SMSCodeView *t = _arrayTextFidld[i];
        t.text = @"";
        if (i == 0) {
            t.showCursor = YES;
        } else {
            t.showCursor = NO;
        }
    }
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
}


@end

SMSCodeView.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface SMSCodeView : UIView

///文字
@property (nonatomic, strong) NSString *text;

///显示光标 默认关闭
@property (nonatomic) BOOL showCursor;

@end

NS_ASSUME_NONNULL_END

SMSCodeView.m

#import "SMSCodeView.h"

@interface SMSCodeView ()

@property (nonatomic, strong) UILabel *label;

@property (nonatomic, strong) UIView *line;

@property (nonatomic, strong) UIView *cursor;

@end

@implementation SMSCodeView

- (instancetype)init {
    self = [super init];
    if (self) {
        [self config];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self config];
    }
    return self;
}

- (void)config {
    
    self.userInteractionEnabled = NO;
    
    _line = [[UIView alloc] init];
    _line.userInteractionEnabled = NO;
    _line.backgroundColor = UIColor.grayColor;
    [self addSubview:_line];
    
    _label = [[UILabel alloc] init];
    _label.textColor = UIColor.blackColor;
    [self addSubview:_label];
    
    //默认关闭
    _showCursor = NO;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.line.frame = CGRectMake(0, self.frame.size.height - 1, self.frame.size.width, 1);
    CGFloat x = (self.frame.size.width - self.label.frame.size.width) / 2.0;
    CGFloat y = (self.frame.size.height - self.label.frame.size.height) / 2.0;
    self.label.frame = CGRectMake(x, y, self.label.frame.size.width, self.label.frame.size.height);
    
    [self updateCursorFrame];
}

- (void)setText:(NSString *)text {
    _text = text;
    if (_text.length > 0) {
        _line.backgroundColor = UIColor.redColor;
    } else {
        _line.backgroundColor = UIColor.grayColor;
    }
    _label.text = text;
    [self.label sizeToFit];
    [self setNeedsLayout];
    [self layoutIfNeeded];
}

- (void)updateCursorFrame {
    CGFloat x = 0;
    if (self.label.frame.size.width <= 0) {
        x = (self.frame.size.width - 1.6) / 2.0;
    } else {
        x = CGRectGetMaxX(self.label.frame);
    }
    _cursor.frame = CGRectMake(x, 10, 1.6, self.frame.size.height - 20);
}

- (void)setShowCursor:(BOOL)showCursor {
    
    if (_showCursor == YES && showCursor == YES) { //重复开始, 那么,什么也不做
    } else if (_showCursor == YES && showCursor == NO) { //原来是开始的, 现在要求关闭, 那么,就关闭
        [_cursor removeFromSuperview];
    } else if (_showCursor == NO && showCursor == YES) { //原来是关闭, 现在要求开始, 那么, 开始
        _cursor = [[UIView alloc] init];
        _cursor.userInteractionEnabled = NO;
        _cursor.backgroundColor = UIColor.redColor;
        [self addSubview:_cursor];
        [self updateCursorFrame];
        _cursor.alpha = 0;
        [self animationOne:_cursor];
    } else if (_showCursor == NO && showCursor == NO) { //重复关闭
        [_cursor removeFromSuperview];
    }
    _showCursor = showCursor;
}

// 光标效果
- (void)animationOne:(UIView *)aView {
    [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        aView.alpha = 1;
    } completion:^(BOOL finished) {
        if (self.showCursor) {
            [self performSelector:@selector(animationTwo:) withObject:aView afterDelay:0.5];
        }
    }];
}

- (void)animationTwo:(UIView *)aView {
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        aView.alpha = 0;
    } completion:^(BOOL finished) {
        if (self.showCursor) {
            [self performSelector:@selector(animationOne:) withObject:aView afterDelay:0.1];
        }
    }];
}

@end

在控制器里测试使用

#import "UIViewController.h"
#import "SMSCodeInputView.h"

@interface UIViewController ()

@property (strong, nonatomic) SMSCodeInputView *inputView;

@end

@implementation UIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColor.whiteColor;
    
    self.inputView = [[SMSCodeInputView alloc] initWithFrame:CGRectMake(20, 0, [UIScreen mainScreen].bounds.size.width - 40, 60)];
    [self.view addSubview:self.inputView];
    self.inputView.center = self.view.center;
    
    
    UIButton *b = [[UIButton alloc] init];
    [b setTitle:@"随机更改输入框的个数和间距" forState:UIControlStateNormal];
    b.backgroundColor = UIColor.brownColor;
    b.titleLabel.font = [UIFont systemFontOfSize:14];
    b.frame = CGRectMake(0, 100, 300, 44);
    [b addTarget:self action:@selector(chage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:b];
}

- (void)chage {
    self.inputView.codeCount = arc4random_uniform(8) + 2;
    self.inputView.codeSpace = arc4random_uniform(60) + 10;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self.inputView becomeFirstResponder];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.inputView resignFirstResponder];
    NSLog(@"获取到输入: %@", self.inputView.codeText);
}

@end

结语

好烦惹。

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