iOS 分割输入验证码的视觉效果

article/2025/8/28 10:46:08

通常情况下,在用户注册或者登录的时候我们会用到手机验证码,而有时就会需要,分割输入验证码的视觉效果。

那这种情况,我们怎么实现呢?

在网上查了很多,好多都只是给了实现代码,给的东西都不是很详细,粘贴过来,有好多值不知道是从哪里来的,还有的就是需要第三方,但是第三方代码量就太多了,会使程序变大,虽然影响不大,但是完全没有必要

下面时我结合网上和自己实现代码,下面配有demo下载链接

先看实现代码:

我们要创建两个类:VertificationCodeInputView 继承 UIView, VertificationCodeInputLabel 继承UILabel

先看VertificationCodeInputView.h文件

@protocol getTextFieldContentDelegate <NSObject>
//返回搜索内容
-(void)returnTextFieldContent:(NSString*)content;
@end@interface VertificationCodeInputView : UIView
@property (assign,nonatomic,readwrite)id <getTextFieldContentDelegate>delegate;
/**背景图片*/
@property (nonatomic,copy)NSString *backgroudImageName;
/**验证码/密码的位数*/
@property (nonatomic,assign)NSInteger numberOfVertificationCode;
/**控制验证码/密码是否密文显示*/
@property (nonatomic,assign)bool secureTextEntry;
/**验证码/密码内容,可以通过该属性拿到验证码/密码输入框中验证码/密码的内容*/
@property (nonatomic,copy)NSString *vertificationCode;-(void)becomeFirstResponder; 

接下来看VertificationCodeInputView.m文件

 

#import "VertificationCodeInputView.h"
#import "VertificationCodeInputLabel.h"@interface VertificationCodeInputView () <UITextFieldDelegate>
/**用于获取键盘输入的内容,实际不显示*/
@property (nonatomic,strong)UITextField *textField;
/**验证码/密码输入框的背景图片*/
@property (nonatomic,strong)UIImageView *backgroundImageView;
/**实际用于显示验证码/密码的label*/
@property (nonatomic,strong)VertificationCodeInputLabel *label;
@end@implementation VertificationCodeInputView- (instancetype)initWithFrame:(CGRect)frame {if (self = [super initWithFrame:frame]) {// 设置透明背景色,保证vertificationCodeInputView显示的frame为backgroundImageView的frameself.backgroundColor = [UIColor clearColor];/* 调出键盘的textField */_textField = [[UITextField alloc]initWithFrame:self.bounds];// 隐藏textField,通过点击IDVertificationCodeInputView使其成为第一响应者,来弹出键盘_textField.hidden =YES;_textField.keyboardType =UIKeyboardTypeNumberPad;_textField.delegate =self;_textField.font = [UIFont systemFontOfSize:25];// 将textField放到最后边[self insertSubview:self.textField atIndex:0];/* 添加用于显示验证码/密码的label */_label = [[VertificationCodeInputLabel alloc]initWithFrame:self.bounds];_label.numberOfVertificationCode =_numberOfVertificationCode;_label.secureTextEntry =_secureTextEntry;_label.font =self.textField.font;[self addSubview:self.label];}return self;
}#pragma mark --------- 设置背景图片
- (void)setBackgroudImageName:(NSString *)backgroudImageName {_backgroudImageName = backgroudImageName;// 若用户设置了背景图片,则添加背景图片self.backgroundImageView = [[UIImageView alloc]initWithFrame:self.bounds];self.backgroundImageView.image = [UIImage imageNamed:self.backgroudImageName];// 将背景图片插入到label的后边,避免遮挡验证码/密码的显示[self insertSubview:self.backgroundImageView belowSubview:self.label];
}- (void)setNumberOfVertificationCode:(NSInteger)numberOfVertificationCode {_numberOfVertificationCode = numberOfVertificationCode;// 保持label的验证码/密码位数与IDVertificationCodeInputView一致,此时label一定已经被创建self.label.numberOfVertificationCode =_numberOfVertificationCode;
}- (void)setSecureTextEntry:(bool)secureTextEntry {_secureTextEntry = secureTextEntry;self.label.secureTextEntry =_secureTextEntry;
}-(void)becomeFirstResponder{[self.textField becomeFirstResponder];
}- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {[self.textField becomeFirstResponder];
}#pragma mark ------ 时时监测输入框的内容- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {// 判断是不是“删除”字符if (string.length !=0) {//不是“删除”字符// 判断验证码/密码的位数是否达到预定的位数if (textField.text.length <self.numberOfVertificationCode) {self.label.text = [textField.text stringByAppendingString:string];self.vertificationCode =self.label.text;if (self.label.text.length == _numberOfVertificationCode) {/******* 通过协议将验证码返回当前页面  ******/if ([_delegate respondsToSelector:@selector(returnTextFieldContent:)]){[_delegate returnTextFieldContent:_vertificationCode];}}return YES;} else {return NO;}} else {//是“删除”字符self.label.text = [textField.text substringToIndex:textField.text.length -1];self.vertificationCode =self.label.text;return YES;}
}

在下来就是VertificationCodeInputLabel.h


/**验证码/密码的位数*/
@property (nonatomic,assign)NSInteger numberOfVertificationCode;/**控制验证码/密码是否密文显示*/
@property (nonatomic,assign)bool secureTextEntry; 

在下来就是.m文件

#import "VertificationCodeInputLabel.h"//设置边框宽度,值越大,边框越粗
#define ADAPTER_RATE_WIDTH 1
//设置是否有边框,等于 1 时 是下划线  大于1 的时候随着值越大,边框越大,
#define ADAPTER_RATE_HIDTH 1@implementation VertificationCodeInputLabel//重写setText方法,当text改变时手动调用drawRect方法,将text的内容按指定的格式绘制到label上
- (void)setText:(NSString *)text {[super setText:text];// 手动调用drawRect方法[self setNeedsDisplay];
}// 按照指定的格式绘制验证码/密码
- (void)drawRect:(CGRect)rect1 {//计算每位验证码/密码的所在区域的宽和高CGRect rect =CGRectMake(0,0,200,45);float width = rect.size.width / (float)self.numberOfVertificationCode;float height = rect.size.height;// 将每位验证码/密码绘制到指定区域for (int i =0; i <self.text.length; i++) {// 计算每位验证码/密码的绘制区域CGRect tempRect =CGRectMake(i * width,0, width, height);if (_secureTextEntry) {//密码,显示圆点UIImage *dotImage = [UIImage imageNamed:@"dot"];// 计算圆点的绘制区域CGPoint securityDotDrawStartPoint =CGPointMake(width * i + (width - dotImage.size.width) /2.0, (tempRect.size.height - dotImage.size.height) / 2.0);// 绘制圆点[dotImage drawAtPoint:securityDotDrawStartPoint];} else {//验证码,显示数字// 遍历验证码/密码的每个字符NSString *charecterString = [NSString stringWithFormat:@"%c", [self.text characterAtIndex:i]];// 设置验证码/密码的现实属性NSMutableDictionary *attributes = [[NSMutableDictionary alloc]init];attributes[NSFontAttributeName] =self.font;// 计算每位验证码/密码的绘制起点(为了使验证码/密码位于tempRect的中部,不应该从tempRect的重点开始绘制)// 计算每位验证码/密码的在指定样式下的sizeCGSize characterSize = [charecterString sizeWithAttributes:attributes];CGPoint vertificationCodeDrawStartPoint =CGPointMake(width * i + (width - characterSize.width) /2.0, (tempRect.size.height - characterSize.height) /2.0);// 绘制验证码/密码[charecterString drawAtPoint:vertificationCodeDrawStartPoint withAttributes:attributes];}}//绘制底部横线for (int k=0; k<self.numberOfVertificationCode; k++) {[self drawBottomLineWithRect:rect andIndex:k];[self drawSenterLineWithRect:rect andIndex:k];}}//绘制底部的线条
- (void)drawBottomLineWithRect:(CGRect)rect1 andIndex:(int)k{CGRect rect =CGRectMake(0,0,200,45);float width = rect.size.width / (float)self.numberOfVertificationCode;float height = rect.size.height;//1.获取上下文CGContextRef context =UIGraphicsGetCurrentContext();//2.设置当前上下问路径CGFloat lineHidth =0.25 * ADAPTER_RATE_WIDTH;CGFloat strokHidth =0.5 * ADAPTER_RATE_HIDTH;CGContextSetLineWidth(context, lineHidth);if ( k<=self.text.length ) {CGContextSetStrokeColorWithColor(context,[UIColor greenColor].CGColor);//底部颜色CGContextSetFillColorWithColor(context,[UIColor greenColor].CGColor);//内容的颜色}else{CGContextSetStrokeColorWithColor(context,[UIColor redColor].CGColor);//底部颜色CGContextSetFillColorWithColor(context,[UIColor greenColor].CGColor);//内容的颜色}CGRect rectangle =CGRectMake(k*width+width/10,height-lineHidth-strokHidth,width-width/5,strokHidth);CGContextAddRect(context, rectangle);CGContextStrokePath(context);
}//绘制中间的输入的线条
- (void)drawSenterLineWithRect:(CGRect)rect1 andIndex:(int)k{if ( k==self.text.length ) {CGRect rect =CGRectMake(0,0,200,45);float width = rect.size.width / (float)self.numberOfVertificationCode;float height = rect.size.height;//1.获取上下文CGContextRef context =UIGraphicsGetCurrentContext();CGContextSetLineWidth(context,0.5);/****  设置竖线的颜色 ****/CGContextSetStrokeColorWithColor(context,[UIColor greenColor].CGColor);//CGContextSetFillColorWithColor(context,[UIColor greenColor].CGColor);CGContextMoveToPoint(context, width * k + (width -1.0) /2.0, height/5);CGContextAddLineToPoint(context,  width * k + (width -1.0) /2.0,height-height/5);CGContextStrokePath(context);}
}


以上这些就是实现代码,接下来是调用

#import "ViewController.h"
#import "VertificationCodeInputView.h"
@interface ViewController ()<getTextFieldContentDelegate>{VertificationCodeInputView *vertificationCodeInputView;
}
@end@implementation ViewController
- (void)viewDidLoad {[super viewDidLoad];self.view.backgroundColor = [UIColor whiteColor];vertificationCodeInputView = [[VertificationCodeInputView alloc]initWithFrame:CGRectMake(50,250,200,45)];vertificationCodeInputView.delegate = self;/****** 设置验证码/密码的位数默认为四位 ******/ vertificationCodeInputView.numberOfVertificationCode = 6;/*********验证码(显示数字)YES,隐藏形势 NO,数字形式**********/ vertificationCodeInputView.secureTextEntry =NO;[self.view addSubview:vertificationCodeInputView];[vertificationCodeInputView becomeFirstResponder];
}#pragma mark --------- 获取验证码
-(void)returnTextFieldContent:(NSString *)content{NSLog(@"%@================验证码",content);
}- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.
}@end


CSDN  下载链接:分割验证码 

GitHub下载链接:Swift 加OC版本


http://chatgpt.dhexx.cn/article/0F1oGbxr.shtml

相关文章

input输入框模拟验证码输入效果

今天看到一个帖子&#xff0c;说到用input输入框模拟滴滴、摩拜等app验证码输入效果&#xff0c;提到了一个方案&#xff1a; 1、利用input来获得焦点&#xff0c;自动调用手机的数字键盘 2、实际将输入框用透明度隐藏 3、用label的for属性与input联动来显示输入的数字 于是…

vue实现验证码输入

需求&#xff1a;这种样式的验证码输入&#xff0c;进入页面时光标停留在第一个格子&#xff0c;随着输入的数字向后移动。 实现逻辑&#xff1a; ①首先考虑样式&#xff0c;将六个格子及获取光标的样式写出来。 ②需要一个input框作为输入&#xff0c;所以在页面上加input框&…

爬虫验证码-手动输入

一般网站登录的时候会有验证码的问题,下面是将验证码下载到本地,手动输入模拟登录。在请求的时候使用会话是为了保证获取的验证码、表单令牌等数据一致 import requestsfrom bs4 import BeautifulSoupheaders = {User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWeb…

小程序多个输入框输入验证码功能 实现

老套路,先上图 <view class"check"><!-- 输入核验码 --><view class"query"><view class"query_item_name">请输入核验码</view><view class"query_num_block"><input typenumber class"…

手机计算机上输入错误是什么意思,电脑输入验证码总是提示错误该怎么解决?...

不少同学都遇到过在页面中输入验证码总是错误的问题&#xff0c;并且不管更换几次验证码图片&#xff0c;依然提示验证码错误&#xff0c;着实影响心情&#xff0c;接下来小编总结了一部分造成验证码总是错误的原因以及解决办法&#xff0c;希望对大家有所帮助; 第一种&#xf…

Python模拟登陆古诗文网手动输入验证码显示验证码错误

Python模拟登陆古诗文网手动输入验证码显示验证码错误 import requests from lxml import etree sessionrequests.Session() headers {User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36,}…

自定义验证码输入框:VerificationCodeView

先上两张效果图&#xff1a; 1.java类&#xff1a; package com...ui;import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.text…

案例:登录中输入验证码(Session及JSP技术应用)

案例&#xff1a;登录中输入验证码(会话技术) 1.案例需求&#xff1a;1.访问带有验证码的登录页面login.jsp2.用户输入用户名&#xff0c;密码以及验证码如果用户和密码输入有误&#xff0c;跳转登录页面。提示&#xff1a;用户或密码错误如果验证码输入有误&#xff0c;跳转登…