iOS开发

ios 生成随机验证码

2018-04-13  本文已影响0人  壮士你怎么了
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
上一篇下一篇

猜你喜欢

热点阅读