IOS 图形验证码

先给大家摆上效果图。

1.自定义MQVerCodeInputView类 继承 UIView

MQVerCodeInputView.h 文件中:

#import <UIKit/UIKit.h>

typedefvoid(^MQTextViewBlock)(NSString*text);

@interfaceMQVerCodeInputView :UIView

@property(nonatomic,assign)UIKeyboardTypekeyBoardType;

@property(nonatomic,copy)MQTextViewBlockblock;

/*验证码的最大长度*/

@property(nonatomic,assign)NSIntegermaxLenght;

/*未选中下的view的borderColor*/

@property(nonatomic,strong)UIColor*viewColor;

/*选中下的view的borderColor*/

@property(nonatomic,strong)UIColor*viewColorHL;

-(void)mq_verCodeViewWithMaxLenght;

@end

2.UIView+MQ创建类目文件

UIView+MQ.h文件:

#import <UIKit/UIKit.h>

@interfaceUIView (MQ)

@property(nonatomic)IBInspectableCGFloatcornerRadius;

/**头像圆角*/

@property(nonatomic)IBInspectableBOOLavatarCorner;

/**边框*/

@property(nonatomic)IBInspectableCGFloatborderWidth;

/**边框颜色*/

@property(nonatomic,strong)IBInspectableUIColor*borderColor;

+ (__kindofUIView*)MQLoadNibView;

- (void)MQSetViewCircleWithBorderWidth:(CGFloat) width andColor:(UIColor*)borColor;

- (void)MQViewSetCornerRadius:(CGFloat)radius;

@end


UIView+MQ.m文件:

#import"UIView+MQ.h"

#import <objc/runtime.h>

@implementationUIView (MQ)

- (CGFloat)cornerRadius

{

return[objc_getAssociatedObject(self,@selector(cornerRadius))floatValue];

}

- (void)setCornerRadius:(CGFloat)cornerRadius

{

self.layer.cornerRadius= cornerRadius;

self.layer.masksToBounds= (cornerRadius >0);

}

- (BOOL)avatarCorner{

return[objc_getAssociatedObject(self,@selector(cornerRadius))floatValue] >0;

}

- (void)setAvatarCorner:(BOOL)corner{

if(corner){

self.layer.cornerRadius=CGRectGetWidth(self.frame)/2;

self.layer.masksToBounds= corner;

}

}

- (CGFloat)borderWidth{

return[objc_getAssociatedObject(self,@selector(borderWidth))floatValue];

}

- (void)setBorderWidth:(CGFloat)borderWidth{

self.layer.borderWidth= borderWidth;

self.layer.masksToBounds= (borderWidth >0);

}

- (UIColor*)borderColor{

returnobjc_getAssociatedObject(self,@selector(borderColor));

}

- (void)setBorderColor:(UIColor*)borderColor{

self.layer.borderColor= borderColor.CGColor;

}

+ (__kindofUIView*)MQLoadNibView{

NSString*className =NSStringFromClass([selfclass]);

return[[[UINibnibWithNibName:classNamebundle:nil]instantiateWithOwner:selfoptions:nil]lastObject];

}

-(void)MQViewSetCornerRadius:(CGFloat)radius{

[self.layersetMasksToBounds:YES];

[self.layersetCornerRadius:radius];

}

-(void)MQSetViewCircleWithBorderWidth:(CGFloat) width andColor:(UIColor*)borColor{

[selfMQViewSetCornerRadius:(self.frame.size.height/2)];

self.layer.borderWidth=width;

self.layer.borderColor=[borColorCGColor];

}

@end



3.MQVerCodeInputView.m 文件中:

#import"MQVerCodeInputView.h"

#import"Masonry.h"

#import"UIView+MQ.h"

@interfaceMQVerCodeInputView()

@property(nonatomic,strong)UIView*contairView;

@property(nonatomic,strong)UITextView*textView;

@property(nonatomic,strong)NSMutableArray*viewArr;

@property(nonatomic,strong)NSMutableArray*labelArr;

@property(nonatomic,strong)NSMutableArray*pointlineArr;

@end

@implementationMQVerCodeInputView

-(instancetype)initWithFrame:(CGRect)frame{

self= [superinitWithFrame:frame];

if(self) {

[selfinitDefaultValue];

}

returnself;

}

-(void)initDefaultValue{

//初始化默认值

self.maxLenght=4;

_viewColor= [UIColorcolorWithRed:228/255.0green:228/255.0blue:228/255.0alpha:1];

_viewColorHL= [UIColorcolorWithRed:255/255.0green:70/255.0blue:62/255.0alpha:1];

self.backgroundColor= [UIColorclearColor];

[selfbeginEdit];

}

-(void)mq_verCodeViewWithMaxLenght{

//创建输入验证码view

if(_maxLenght<=0) {

return;

}

if(_contairView) {

[_contairViewremoveFromSuperview];

}

_contairView= [UIViewnew];

_contairView.backgroundColor= [UIColorclearColor];

[selfaddSubview:_contairView];

[_contairViewmas_makeConstraints:^(MASConstraintMaker*make) {

make.height.equalTo(self.mas_height);

make.centerX.equalTo(self);

make.centerY.equalTo(self);

}];

[_contairViewaddSubview:self.textView];

[self.textViewmas_makeConstraints:^(MASConstraintMaker*make) {

make.edges.equalTo(_contairView);

}];

CGFloatpadding = (CGRectGetWidth(self.frame) -_maxLenght*CGRectGetHeight(self.frame))/(_maxLenght-1);

UIView*lastView;

for(inti=0; i

UIView*subView = [UIViewnew];

subView.backgroundColor= [UIColorwhiteColor];

subView.cornerRadius=4;

subView.borderWidth= (0.5);

subView.userInteractionEnabled=NO;

[_contairViewaddSubview:subView];

[subViewmas_makeConstraints:^(MASConstraintMaker*make) {

if(lastView) {

make.left.equalTo(lastView.mas_right).with.offset(padding);

}else{

make.left.equalTo(@(0));

}

make.centerY.equalTo(self.contairView);

make.height.equalTo(self.contairView.mas_height);

make.width.equalTo(self.contairView.mas_height);

}];

UILabel*subLabel = [UILabelnew];

subLabel.font= [UIFontsystemFontOfSize:38];

[subViewaddSubview:subLabel];

[subLabelmas_makeConstraints:^(MASConstraintMaker*make) {

make.centerX.equalTo(subView);

make.centerY.equalTo(subView);

}];

lastView = subView;

UIBezierPath*path = [UIBezierPathbezierPathWithRect:CGRectMake((CGRectGetHeight(self.frame)-2)/2,5,2,(CGRectGetHeight(self.frame)-10))];

CAShapeLayer*line = [CAShapeLayerlayer];

line.path= path.CGPath;

line.fillColor=_viewColorHL.CGColor;

[subView.layeraddSublayer:line];

if(i ==0) {//初始化第一个view为选择状态

[lineaddAnimation:[selfopacityAnimation]forKey:@"kOpacityAnimation"];

line.hidden=NO;

subView.borderColor=_viewColorHL;

}else{

line.hidden=YES;

subView.borderColor=_viewColor;

}

[self.viewArraddObject:subView];

[self.labelArraddObject:subLabel];

[self.pointlineArraddObject:line];

}

[_contairViewmas_makeConstraints:^(MASConstraintMaker*make) {

make.right.equalTo(lastView?lastView.mas_right:@(0));

}];

}

#pragma mark - TextView

-(void)beginEdit{

[self.textViewbecomeFirstResponder];

}

-(void)endEdit{

[self.textViewresignFirstResponder];

}

- (void)textViewDidChange:(UITextView*)textView{

NSLog(@"%@",textView.text);

NSString*verStr = textView.text;

//有空格去掉空格

verStr = [verStrstringByReplacingOccurrencesOfString:@" "withString:@""];

if(verStr.length>=_maxLenght) {

verStr = [verStrsubstringToIndex:_maxLenght];

[selfendEdit];

}

textView.text= verStr;

if(self.block) {

//将textView的值传出去

self.block(verStr);

}

for(inti=0; i

//以text为中介区分

UILabel*label =self.labelArr[i];

if(i

[selfchangeViewLayerIndex:ipointHidden:YES];

label.text= [verStrsubstringWithRange:NSMakeRange(i,1)];

}else{

[selfchangeViewLayerIndex:ipointHidden:i==verStr.length?NO:YES];

if(!verStr&&verStr.length==0) {//textView的text为空的时候

[selfchangeViewLayerIndex:0pointHidden:NO];

}

label.text=@"";

}

}

}

- (void)changeViewLayerIndex:(NSInteger)index pointHidden:(BOOL)hidden{

UIView*view =self.viewArr[index];

view.borderColor= hidden?_viewColor:_viewColorHL;

CAShapeLayer*line =self.pointlineArr[index];

if(hidden) {

[lineremoveAnimationForKey:@"kOpacityAnimation"];

}else{

[lineaddAnimation:[selfopacityAnimation]forKey:@"kOpacityAnimation"];

}

line.hidden= hidden;

}

- (CABasicAnimation*)opacityAnimation {

CABasicAnimation*opacityAnimation = [CABasicAnimationanimationWithKeyPath:@"opacity"];

opacityAnimation.fromValue=@(1.0);

opacityAnimation.toValue=@(0.0);

opacityAnimation.duration=0.9;

opacityAnimation.repeatCount=HUGE_VALF;

opacityAnimation.removedOnCompletion=YES;

opacityAnimation.fillMode=kCAFillModeForwards;

opacityAnimation.timingFunction=[CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionEaseIn];

returnopacityAnimation;

}

#pragma mark --setter&&getter

-(void)setMaxLenght:(NSInteger)maxLenght{

_maxLenght= maxLenght;

}

-(void)setKeyBoardType:(UIKeyboardType)keyBoardType{

_keyBoardType= keyBoardType;

self.textView.keyboardType= keyBoardType;

}

-(void)setViewColor:(UIColor*)viewColor{

_viewColor= viewColor;

}

-(void)setViewColorHL:(UIColor*)viewColorHL{

_viewColorHL= viewColorHL;

}

-(UITextView*)textView{

if(!_textView) {

_textView= [UITextViewnew];

_textView.tintColor= [UIColorclearColor];

_textView.backgroundColor= [UIColorclearColor];

_textView.textColor= [UIColorclearColor];

_textView.delegate=self;

_textView.keyboardType=UIKeyboardTypeDefault;

_textView.autocorrectionType=UITextAutocorrectionTypeNo;//取消自动联想功能

}

return_textView;

}

-(NSMutableArray*)pointlineArr{

if(!_pointlineArr) {

_pointlineArr= [NSMutableArraynew];

}

return_pointlineArr;

}

-(NSMutableArray*)viewArr{

if(!_viewArr) {

_viewArr= [NSMutableArraynew];

}

return_viewArr;

}

-(NSMutableArray*)labelArr{

if(!_labelArr) {

_labelArr= [NSMutableArraynew];

}

return_labelArr;

}

@end



4.自定义文件写好后,在你需要使用的地方调用即刻~

定义外部属性,

MQVerCodeInputView*verView;//自定义验证码

NSString*code;//输入的验证码


点击图形验证码,调用此方法   传入后台请求的图片,转成NSData*类型。

#pragma mark -弹出验证码输入框

-(void)showGraphicalVerificationCode:(NSData*)data{

[self tapBut];

maskView= [[UIViewalloc]initWithFrame:CGRectMake(0,0,SCREENWIDTH,SCREENHEIGHT)];

maskView.backgroundColor= [UIColorblackColor];

maskView.alpha=0.5;

[self.viewaddSubview:maskView];

UITapGestureRecognizer*tapGesture = [[UITapGestureRecognizeralloc]initWithTarget:selfaction:@selector(tapBut)];

[maskViewaddGestureRecognizer:tapGesture];

imageBtn= [[UIButtonalloc]initWithFrame:CGRectMake(0,0,SCREENWIDTH-50-80,60)];

imageBtn.centerX=maskView.centerX;

imageBtn.centerY=maskView.centerY-80;

imageBtn.layer.masksToBounds=YES;

imageBtn.layer.cornerRadius=4;

[imageBtnsetBackgroundImage:[UIImageimageWithData:data]forState:UIControlStateNormal];

[imageBtnaddTarget:selfaction:@selector(ImageChange:)forControlEvents:UIControlEventTouchUpInside];

[self.viewaddSubview:imageBtn];

__weaktypeof(self) weakSelf =self;

verView= [[MQVerCodeInputViewalloc]initWithFrame:CGRectMake(0,0,SCREENWIDTH-50-80,50)];

verView.maxLenght=4;//最大长度

verView.keyBoardType=UIKeyboardTypePhonePad;

[verViewmq_verCodeViewWithMaxLenght];

verView.block= ^(NSString*text){

NSLog(@"text = %@",text);

if(text.length==4) {

labelText= text;

[weakSelfgetPhoneVerificationCode];

}

};

verView.center=maskView.center;

[self.viewaddSubview:verView];

}


#pragma mark -移除验证码输入框

-(void)tapBut{

[maskViewremoveFromSuperview];

[verViewremoveFromSuperview];

[imageBtnremoveFromSuperview];

}


附上github  图形验证码Demo地址https://github.com/xuliang0712/iOS-.git

如有问题,欢迎交流~

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

推荐阅读更多精彩内容

  • iOS_autoLayout_Masonry 概述 Masonry是一个轻量级的布局框架与更好的包装AutoLay...
    指尖的跳动阅读 1,144评论 1 4
  • 一、前言 关于苹果的布局一直是我比较纠结的问题,是写代码来控制布局,还是使用storyboard来控制布局呢?以前...
    iplaycodex阅读 2,411评论 0 1
  • 1.NSTimer //暂停if ([timer isValid]) {[timer setFireDate:[N...
    俊月阅读 1,245评论 0 0
  • (一)Masonry介绍 Masonry是一个轻量级的布局框架 拥有自己的描述语法 采用更优雅的链式语法封装自动布...
    木易林1阅读 2,303评论 0 3
  • 我家30张全家福 容月 从结婚到现在,我们已照了30张结婚周年照。最近有同事要看,我便与她们一起仔细看了一遍,发现...
    容月阅读 338评论 0 2