您的位置:首页 > 移动开发 > IOS开发

iOS 随机验证码(无干扰线)

2015-09-29 09:50 501 查看
1、在.h文件中定义两个属性:

//  属性声明
@property(nonatomic,retain)UILabel *checkCodeNumberLabel;// 显示验证码Label
@property(nonatomic,copy)NSString *code;// 随机获得的验证码


2、在.m 文件宏定义验证码的宽和高:

#define SW self.checkCodeNumberLabel.frame.size.width
#define SH self.checkCodeNumberLabel.frame.size.height


3、在viewDidLoad 中设置self.view 的背景颜色、设置显示验证码的位置。这里添加点击手势,你可以添加按钮来触发生成验证码的方法

//  初始化 视图
- (void)creatViewss
{
self.view.backgroundColor = [UIColor colorWithRed:0.287green:0.778blue:0.832alpha:1.000];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:selfaction:@selector(produceCode:)];
self.checkCodeNumberLabel = [[UILabel alloc]initWithFrame:CGRectMake(50,200,100,30)];
[self.viewaddSubview:self.checkCodeNumberLabel];
[self.viewaddGestureRecognizer:tap];
}


4、点击任意地方触发生成验证码方法

- (void)produceCode:(UITapGestureRecognizer*)tap
{
for(UIView*viewinself.checkCodeNumberLabel.subviews)
{
[view removeFromSuperview];
}
//  生成背景颜色
float red = arc4random()%100/100.0;
float green = arc4random()%100/100.0;
float blue = arc4random()%100/100.0;
UIColor*color = [UIColor colorWithRed:redgreen:greenblue:bluealpha:0.3];
[self.checkCodeNumberLabel setBackgroundColor:color];
//  生成文字
constintcount =6;// 修改这里可以选择自己想要得验证码位数
chardata[count];
for (inti = 0;i < count; i ++)
{
int j = '0' + (arc4random_uniform(75));
if ((j >= 58 &&j <= 64)||(j >= 91 &&j <= 96))
{
--i;
}
else
{
data[i] = (char)j;
}
}
NSString*text = [[NSString alloc]initWithBytes:datalength:countencoding:NSUTF8StringEncoding];
#pragmamark--------获得字符self.code随机验证码--------------
NSLog(@"-----------------------------------------");
self.code =text;
NSLog(@"code:%@",self.code);
#pragmamark--------获得字符的尺寸--------------
CGSizecSize =CGSizeFromString(@"B");
int width = SW/text.length-cSize.width*text.length-10;
int height = SH-cSize.height*text.length;
//   intheight =SH+cSize.height*text.length;
CGPointpoint;
floatpX,pY;
for (inta =0,count = (int)text.length;a < count;a ++)
{
pX =arc4random()%width+SW/text.length*a-1;
pY =arc4random()%height;
point =CGPointMake(pX,pY);
UILabel*tempLabel = [[UILabel alloc]initWithFrame:CGRectMake(pX,0,SW/4,SH)];
tempLabel.backgroundColor = [UIColor clearColor];
//  字体颜色额
float red = arc4random()%100/100.0;
float green = arc4random()%100/100.0;
float blue = arc4random()%100/100.0;
UIColor*color = [UIColor colorWithRed:redgreen:greenblue:bluealpha:1.0];
NSString*textC = [NSStringstringWithFormat:@"%c",data[a]];
tempLabel.textColor =color;
tempLabel.text =textC ;
[self.checkCodeNumberLabel addSubview:tempLabel];
}
}


5、到这里验证码的方法就OK了,需要多少为的验证码把
count 的值修改一下就可以了。

效果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: