iOS本地动态生成验证码的方法
发布时间 - 2026-01-10 22:18:55 点击率:次前几天app注册被人攻击了,从网上找了这个先保存下。。。。

用于ios本地动态生成验证码,效果如下:
- 导入CoreGraphics.framework
用于绘制图形
- 封装UIView,便捷使用,代码如下:
AuthcodeView.h
#import <UIKit/UIKit.h>
@interface AuthcodeView : UIView
@property (strong, nonatomic) NSArray *dataArray;//字符素材数组
@property (strong, nonatomic) NSMutableString *authCodeStr;//验证码字符串
@end
AuthcodeView.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 6
#define kFontSize [UIFont systemFontOfSize:arc4random() % 5 + 15]
@implementation AuthcodeView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
- (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",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",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
- 界面添加验证码
@interface AuthCodeViewController ()<UITextFieldDelegate, UIAlertViewDelegate>
{
AuthcodeView *authCodeView;
UITextField *_input;
}
@end
@implementation AuthCodeViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
//显示验证码界面
authCodeView = [[AuthcodeView alloc] initWithFrame:CGRectMake(30, 100, self.view.frame.size.width-60, 40)];
[self.view addSubview:authCodeView];
//提示文字
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 160, self.view.frame.size.width-100, 40)];
label.text = @"点击图片换验证码";
label.font = [UIFont systemFontOfSize:12];
label.textColor = [UIColor grayColor];
[self.view addSubview:label];
//添加输入框
_input = [[UITextField alloc] initWithFrame:CGRectMake(30, 220, self.view.frame.size.width-60, 40)];
_input.layer.borderColor = [UIColor lightGrayColor].CGColor;
_input.layer.borderWidth = 2.0;
_input.layer.cornerRadius = 5.0;
_input.font = [UIFont systemFontOfSize:21];
_input.placeholder = @"请输入验证码!";
_input.clearButtonMode = UITextFieldViewModeWhileEditing;
_input.backgroundColor = [UIColor clearColor];
_input.textAlignment = NSTextAlignmentCenter;
_input.returnKeyType = UIReturnKeyDone;
_input.delegate = self;
[self.view addSubview:_input];
}
#pragma mark 输入框代理,点击return 按钮
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//判断输入的是否为验证图片中显示的验证码
if ([_input.text isEqualToString:authCodeView.authCodeStr])
{
//正确弹出警告款提示正确
UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"恭喜您 ^o^" message:@"验证成功" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alview show];
}
else
{
//验证不匹配,验证码和输入框抖动
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
anim.repeatCount = 1;
anim.values = @[@-20,@20,@-20];
// [authCodeView.layer addAnimation:anim forKey:nil];
[_input.layer addAnimation:anim forKey:nil];
}
return YES;
}
#pragma mark 警告框中方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//清空输入框内容,收回键盘
if (buttonIndex==0)
{
_input.text = @"";
[_input resignFirstResponder];
}
}
以上所述是小编给大家介绍的iOS本地动态生成验证码的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
# ios本地生成验证码
# iOS开发实现随机图片验证码封装
# iOS 生成图片验证码绘制实例代码
# iOS 生成图片验证码(实用功能)
# 利用iOS绘制图片生成随机验证码示例代码
# IOS实现验证码倒计时功能(一)
# iOS获取短信验证码倒计时的两种实现方法
# IOS实现验证码倒计时功能(二)
# iOS生成图片数字字母验证效果
# 验证码
# 输入框
# 小编
# 在此
# 被人
# 给大家
# 请输入
# 弹出
# 找了
# 前几天
# 来实现
# 所述
# 给我留言
# 框中
# 感谢大家
# 会向
# 清空
# 组中
# 不匹配
# 疑问请
相关栏目:
【
网站优化151355 】
【
网络推广146373 】
【
网络技术251813 】
【
AI营销90571 】
相关推荐:
laravel怎么为API路由添加签名中间件保护_laravel API路由签名中间件保护方法
利用vue写todolist单页应用
如何快速搭建安全的FTP站点?
如何用好域名打造高点击率的自主建站?
猪八戒网站制作视频,开发一个猪八戒网站,大约需要多少?或者自己请程序员,需要什么程序员,多少程序员能完成?
JavaScript常见的五种数组去重的方式
如何为不同团队 ID 动态生成多个“认领值班”按钮
通义万相免费版怎么用_通义万相免费版使用方法详细指南【教程】
北京企业网站设计制作公司,北京铁路集团官方网站?
高端网站建设与定制开发一站式解决方案 中企动力
如何挑选高效建站主机与优质域名?
香港服务器部署网站为何提示未备案?
Laravel怎么实现验证码(Captcha)功能
详解vue.js组件化开发实践
深圳网站制作的公司有哪些,dido官方网站?
免费制作统计图的网站有哪些,如何看待现如今年轻人买房难的情况?
音响网站制作视频教程,隆霸音响官方网站?
Java解压缩zip - 解压缩多个文件或文件夹实例
Laravel如何使用Service Provider注册服务_Laravel服务提供者配置与加载
悟空识字怎么关闭自动续费_悟空识字取消会员自动扣费步骤
常州企业网站制作公司,全国继续教育网怎么登录?
Laravel如何实现邮件验证激活账户_Laravel内置MustVerifyEmail接口配置【步骤】
头像制作网站在线观看,除了站酷,还有哪些比较好的设计网站?
Laravel Eloquent关联是什么_Laravel模型一对一与一对多关系精讲
Android中Textview和图片同行显示(文字超出用省略号,图片自动靠右边)
百度输入法ai面板怎么关 百度输入法ai面板隐藏技巧
Laravel Facade的原理是什么_深入理解Laravel门面及其工作机制
国美网站制作流程,国美电器蒸汽鍋怎么用官方网站?
原生JS获取元素集合的子元素宽度实例
手机钓鱼网站怎么制作视频,怎样拦截钓鱼网站。怎么办?
Android中AutoCompleteTextView自动提示
php8.4header发送头信息失败怎么办_php8.4header函数问题解决【解答】
Laravel如何实现事件和监听器?(Event & Listener实战)
韩国网站服务器搭建指南:VPS选购、域名解析与DNS配置推荐
如何快速查询网址的建站时间与历史轨迹?
Laravel如何使用Laravel Vite编译前端_Laravel10以上版本前端静态资源管理【教程】
谷歌浏览器下载文件时中断怎么办 Google Chrome下载管理修复
如何在阿里云虚拟机上搭建网站?步骤解析与避坑指南
PHP 实现电台节目表的智能时间匹配与今日/明日轮播逻辑
香港服务器如何优化才能显著提升网站加载速度?
Laravel如何实现用户角色和权限系统_Laravel角色权限管理机制
小视频制作网站有哪些,有什么看国内小视频的网站,求推荐?
标题:Vue + Vuex 项目中正确使用 JWT 进行身份认证的实践指南
如何为不同团队 ID 动态生成多个非值班状态按钮
网站制作壁纸教程视频,电脑壁纸网站?
东莞市网站制作公司有哪些,东莞找工作用什么网站好?
如何快速生成凡客建站的专业级图册?
Laravel怎么实现验证码功能_Laravel集成验证码库防止机器人注册
Laravel如何发送系统通知_Laravel Notifications实现多渠道消息通知
如何解决hover在ie6中的兼容性问题
下一篇:天翼超高清点击登录位置在哪
下一篇:天翼超高清点击登录位置在哪

