ios 生成随机验证码

6D4B16D068485F541F2DCD66AD8E70AC.jpg

本地生成随机验证码
直接贴代码 -

@property (nonatomic, retain) UIView *view_b;   ///图形验证
@property (nonatomic, retain) AuthcodeView *authCodeView;///图形验证
@property (nonatomic, retain) UIButton *sureBtn;
@property (nonatomic, retain) UITextField *textField_yz; ///图形验证输入框

///1.点击获取验证码按钮,加载实现图形验证码的 view
 /**
 * 获取验证码
 */
-(void) getverificationBtn:(UIButton *)sender
{
    [self addNumYanZheng];
}

///2.图形验证码 view
-(void)addNumYanZheng
{   
    UIView *view_b = [[UIView alloc]init];
    view_b.frame = CGRectMake(0, KStatusBarHeight, kScreenWidth, kScreenHeight - KStatusBarHeight);
    view_b.backgroundColor = RgbColor(0, 0, 0, 0.5);
    _view_b = view_b;
    _view_b.hidden = NO;
    [self.view addSubview:_view_b];
    
    UIView *view_yz = [[UIView alloc]init];
    view_yz.width = 280;
    view_yz.height = 165;
    view_yz.centerX = view_b.centerX;
    view_yz.centerY = view_b.centerY - 66;
    view_yz.layer.cornerRadius = 8;
    view_yz.backgroundColor = [UIColor whiteColor];
    [_view_b addSubview:view_yz];
    
    UILabel *label_title = [[UILabel alloc]init];
    label_title.text = @"请输入图形验证码";
    label_title.textColor = [UIColor blackColor];
    label_title.font = [UIFont systemFontOfSize:16.0];
    label_title.frame = CGRectMake(0, 15, view_yz.width, 16);
    label_title.textAlignment = NSTextAlignmentCenter;
    [view_yz addSubview:label_title];
    
    UIButton *refreshBtn = [[UIButton alloc]init];
    refreshBtn.frame = CGRectMake(view_yz.width - 7 - 26, 7, 26, 26);
    [refreshBtn setImage:[UIImage imageNamed:@"closeyam"] forState:UIControlStateNormal];
    refreshBtn.backgroundColor = [UIColor clearColor];
    [refreshBtn addTarget:self action:@selector(toCloseYZBtn:) forControlEvents:UIControlEventTouchUpInside];
    [view_yz addSubview:refreshBtn];
    
    UIView *view_in = [[UIView alloc]init];
    view_in.width = 250;
    view_in.height = 44;
    view_in.x = 15;
    view_in.y = 45;
    view_in.layer.cornerRadius = 8;
    view_in.backgroundColor = kRGBColor(245, 245, 245);
    [view_yz addSubview:view_in];
    
    UITextField *textField_yz = [[UITextField alloc]init];
    textField_yz.frame = CGRectMake(15, 0, 130, 44);
    textField_yz.placeholder = @"请输入图形验证码";
    [textField_yz setEnabled:NO];
    textField_yz.font = [UIFont systemFontOfSize:14];
    textField_yz.delegate = self;
    textField_yz.enabled = YES;
    textField_yz.keyboardType = UIKeyboardTypeNumberPad;
    textField_yz.clearsOnBeginEditing = NO;
    textField_yz.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textField_yz = textField_yz;
    [view_in addSubview:textField_yz];
    
    //显示验证码界面
    _authCodeView = [[AuthcodeView alloc] initWithFrame:CGRectMake(view_in.width - 15 - 70, 7, 70, 30)];
    [view_in addSubview:_authCodeView];
    
    _sureBtn = [[UIButton alloc]init];
    _sureBtn.frame = CGRectMake(15, view_in.bottom + 15, 250, 44);
    [_sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    _sureBtn.layer.cornerRadius = 10;
    _sureBtn.titleLabel.textColor = [UIColor whiteColor];
    [_sureBtn setBackgroundImage:[self imageWithColor:kRGBColor(230, 0, 1)] forState:UIControlStateNormal];
    [_sureBtn setBackgroundImage:[self imageWithColor:kRGBColor(214, 0, 1)] forState:UIControlStateHighlighted];
    [_sureBtn addTarget:self action:@selector(touchMakeSureYZ:) forControlEvents:UIControlEventTouchUpInside];
    [view_yz addSubview:_sureBtn];
}

/**
 * 关闭图形验证
 */
-(void)toCloseYZBtn:(UIButton*)sender
{
    NSLog(@"关闭图形验证");
    _view_b.hidden = YES;
    [_textField_yz resignFirstResponder];
}

/**
 * 确定图形验证
 */
-(void)touchMakeSureYZ:(UIButton*)sender
{
    NSLog(@"确定图形验证");
    [_textField_yz resignFirstResponder];
    if ([_textField_yz.text isEqualToString:_authCodeView.authCodeStr])
    {
        [self loginPasswordIsWorry:@"验证成功"];
        
        /** 延迟1秒,让按钮变灰 */
        int64_t delayInSeconds = 3.0;      // 延迟的时间
        /*
         *@parameter 1,时间参照,从此刻开始计时
         *@parameter 2,延时多久,此处为秒级,还有纳秒等。10ull * NSEC_PER_MSEC
         */
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            // do something
            _view_b.hidden = YES;
            NSString *str = @"1";
            if ([str isEqualToString:@"1"]) {
                [self.codeBtn timeFailBeginFrom:60];  /// 倒计时60s
                
                /** 延迟1秒,让按钮变灰 */
                int64_t delayInSeconds = 1.0;      // 延迟的时间
                /*
                 *@parameter 1,时间参照,从此刻开始计时
                 *@parameter 2,延时多久,此处为秒级,还有纳秒等。10ull * NSEC_PER_MSEC
                 */
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    // do something
                    self.codeBtn.backgroundColor = kRGBColor(145, 145, 145);
                });
                
            }else
            {
                [self.codeBtn timeFailBeginFrom:1]; /// 处理请求成功但是匹配不成功的情况,并不需要执行倒计时功能
            }
        });
    }
    else
    {
        [self loginPasswordIsWorry:@"验证码输入错误"];
        //验证不匹配,验证码和输入框抖动
        CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
        anim.repeatCount = 1;
        anim.values = @[@-20,@20,@-20];
        [_textField_yz.layer addAnimation:anim forKey:nil];
        [_authCodeView getAuthcode];
    }
}

/**
 * HUD 提示信息 手机号或者密码错误
 */
- (void)loginPasswordIsWorry:(NSString *)sender
{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.bezelView.backgroundColor = [UIColor blackColor];
    hud.bezelView.alpha = 0.8;
    hud.label.textColor = [UIColor whiteColor];
    hud.bezelView.layer.cornerRadius = 4;
    hud.label.font = [UIFont systemFontOfSize:15.0];
    hud.label.text = NSLocalizedString(sender, @"HUD message title");
    [hud hideAnimated:YES afterDelay:3.f];
}



图形验证码
.h 文件
#import <UIKit/UIKit.h>

@interface AuthcodeView : UIView

@property (strong, nonatomic) NSArray *dataArray;//字符素材数组

@property (strong, nonatomic) NSMutableString *authCodeStr;//验证码字符串

-(void)getAuthcode;


.m 文件

#import "AuthcodeView.h"

#define kRandomColor  [UIColor colorWithRed:arc4random() % 256 / 256.0 green:arc4random() % 256 / 256.0 blue:arc4random() % 256 / 256.0 alpha:1.0];
#define kLineCount 6
#define kLineWidth 1.0
#define kCharCount 4
#define kFontSize [UIFont systemFontOfSize:arc4random() % 5 + 15 weight:15]

@implementation AuthcodeView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.layer.cornerRadius = 5.0f;
        self.layer.masksToBounds = YES;
        self.backgroundColor = kRandomColor;
        
        [self getAuthcode];//获得随机验证码
    }
    return self;
}

#pragma mark 获得随机验证码
- (void)getAuthcode
{
    //字符串素材
    _dataArray = [[NSArray alloc] initWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",nil];
    
    _authCodeStr = [[NSMutableString alloc] initWithCapacity:kCharCount];
    //随机从数组中选取需要个数的字符串,拼接为验证码字符串
    for (int i = 0; i < kCharCount; i++)
    {
        NSInteger index = arc4random() % (_dataArray.count-1);
        NSString *tempStr = [_dataArray objectAtIndex:index];
        _authCodeStr = (NSMutableString *)[_authCodeStr stringByAppendingString:tempStr];
    }
}

#pragma mark 点击界面切换验证码
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self getAuthcode];
    
    //setNeedsDisplay调用drawRect方法来实现view的绘制
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    
    //设置随机背景颜色
    self.backgroundColor = kRandomColor;
    
    //根据要显示的验证码字符串,根据长度,计算每个字符串显示的位置
    NSString *text = [NSString stringWithFormat:@"%@",_authCodeStr];
    
    CGSize cSize = [@"A" sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]}];
    
    int width = rect.size.width/text.length - cSize.width;
    int height = rect.size.height - cSize.height;
    
    CGPoint point;
    
    //依次绘制每一个字符,可以设置显示的每个字符的字体大小、颜色、样式等
    float pX,pY;
    for ( int i = 0; i<text.length; i++)
    {
        pX = arc4random() % width + rect.size.width/text.length * i;
        pY = arc4random() % height;
        point = CGPointMake(pX, pY);
        
        unichar c = [text characterAtIndex:i];
        NSString *textC = [NSString stringWithFormat:@"%C", c];
        
        [textC drawAtPoint:point withAttributes:@{NSFontAttributeName:kFontSize}];
    }
    
    //调用drawRect:之前,系统会向栈中压入一个CGContextRef,调用UIGraphicsGetCurrentContext()会取栈顶的CGContextRef
    CGContextRef context = UIGraphicsGetCurrentContext();
    //设置线条宽度
    CGContextSetLineWidth(context, kLineWidth);
    
    //绘制干扰线
    for (int i = 0; i < kLineCount; i++)
    {
        UIColor *color = kRandomColor;
        CGContextSetStrokeColorWithColor(context, color.CGColor);//设置线条填充色
        
        //设置线的起点
        pX = arc4random() % (int)rect.size.width;
        pY = arc4random() % (int)rect.size.height;
        CGContextMoveToPoint(context, pX, pY);
        //设置线终点
        pX = arc4random() % (int)rect.size.width;
        pY = arc4random() % (int)rect.size.height;
        CGContextAddLineToPoint(context, pX, pY);
        //画线
        CGContextStrokePath(context);
    }
}

@end


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

推荐阅读更多精彩内容