扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
具体代码如下所示:
10年积累的做网站、成都做网站经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站设计后付款的网站建设流程,更有浠水免费网站建设让你可以放心的选择与我们合作。
// // AuthcodeView.h // BSbracelet // // Created by Christopher on 17/5/16. // Copyright © 2017年 ZTracy. All rights reserved. // #import@interface AuthcodeView : UIView @property (strong, nonatomic) NSArray *dataArray;//字符素材数组 @property (strong, nonatomic) NSMutableString *authCodeStr;//验证码字符串 @end // // AuthcodeView.m // BSbracelet // // Created by Christopher on 17/5/16. // Copyright © 2017年 ZTracy. All rights reserved. // #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] @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
总结
以上所述是小编给大家介绍的iOS动态验证码实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对创新互联网站的支持!
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流