Iphone:ios interface, generate random verification code locally

Source: Internet
Author: User

This article blogs, imitating Jerry's education blog post, and on its basis, made a few changes. At the same time in the process of rewriting, the place that you neglect, has been re-recognized, benefited greatly. Article Source: http://www.cnblogs.com/jerehedu/p/4527707.html

In fact, this function is not very practical, but it is necessary for us to comb the small points of knowledge.

First, we need to customize a view, so that we will plot in the inside, init this view, you can directly display, and then encounter, you can "take doctrine".

CodeView.h

@property (nonatomic, Strong) nsmutablestring * changestring;//The string that holds the CAPTCHA

We need a public parameter so that it can be read directly when it is referenced outside. This is used to store: system generated verification code. In the input, we directly use the input string, and changestring directly to compare.

codeview.m

#define Krandomcolor [Uicolor colorwithred:arc4random ()%255/255.0 green:arc4random ()%255/255.0 blue:arc4random ()% 255/255.0 alpha:1.0];

#define KLINECOUNT 6

#define KLINEWIDTH 1.0

#define KCHARCOUNT 6

#define Kfontsize [Uifont systemfontofsize:arc4random ()%5 + 15]

Macros define some frequently used parameters, so that you do not have to write the following code.

Write the. h private variable in. m to store the character array

@interface CodeView () {

Nsarray * changearray;//character footage array

}

@end

Next, set the initial interface of the view, which is what appears when you first enter view

-(Instancetype) initWithFrame: (CGRect) frame{

if (self = [Super Initwithframe:frame]) {

Self.layer.masksToBounds = yes;//hidden boundary

Self.backgroundcolor = Krandomcolor;

Show a random verification code

[Self changecaptcha];

}

return self;

}

Rewrite the Init method so that it will be displayed when the system init.

Get 6 characters and numbers to display

-(void) changecaptcha{

Changearray = [[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];

_changestring = [[nsmutablestring alloc]initwithcapacity:kcharcount];

NSString * Getstr = [[NSString alloc]init];

for (int i = 0; i < Kcharcount; i++) {

Nsinteger index = arc4random ()% (changearray.count-1);

GETSTR = [Changearray objectatindex:index];

_changestring = (nsmutablestring *) [_changestring stringbyappendingstring:getstr];

}

}

How to set a click to better verify code

-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{

[Self changecaptcha];

[Self setneedsdisplay];

}

Drawing background and interference lines

-(void) DrawRect: (CGRect) rect{

[Super Drawrect:rect];

Self.backgroundcolor = Krandomcolor;

Get a verification code string to display, depending on the length, calculate the approximate position of each character display

Cgsize csize = [@ "S" Sizewithattributes:@{nsfontattributename:[uifont systemfontofsize:20]}];

int width = rect.size.width/_changestring.length-csize.width;

int height = rect.size.height-csize.height;

Cgpoint Point;

Once each character is drawn, you can set the font size, color, style of each character displayed

float px,py;

for (int i = 0; i < _changestring.length; i++) {

PX = arc4random ()% width + rect.size.width/_changestring.length*i;

PY = Arc4random ()%height;

Point = Cgpointmake (PX, PY);

Unichar C = [_changestring characteratindex:i];

NSString * TEXTC = [NSString stringwithformat:@ "%c", c];

[TEXTC Drawatpoint:point withattributes:@{nsfontattributename:kfontsize}];

}

Get the cgcontextref on top of the stack

Cgcontextref context = Uigraphicsgetcurrentcontext ();

Cgcontextsetlinewidth (context, klinewidth);

Draw a colored line of interference

for (int i = 0; i < Klinecount; i++) {

CGFloat components[] = {arc4random ()%255/255.0,arc4random ()%255/255.0,arc4random ()%255/255.0,arc4random ()%255/ 255.0};

Cgcontextsetstrokecolor (context, components);

Set the starting point

PX = Arc4random ()% (int) rect.size.width;

PY = Arc4random ()% (int) rect.size.height;

Cgcontextmovetopoint (context, PX, PY);

Set End point

PX = Arc4random ()% (int) rect.size.width;

PY = Arc4random ()% (int) rect.size.height;

Cgcontextaddlinetopoint (context, PX, PY);

Cgcontextstrokepath (context);

}

}

Font size, color, symbol, distance, are random.

There is a place, it should be noted that: drawing, only in the DrawRect method to write only effective, in other places, there is no effect.

In this way, the custom view is OK.

Below, is how to show in the Viewcontroller inside.

Inside the ViewController.h:

@interface viewcontroller:uiviewcontroller<uitextfielddelegate,uialertviewdelegate>

@property (nonatomic, retain) CodeView * CodeView;

@property (nonatomic, retain) Uitextfield * Inputtextfield;

@end

To follow two agents, Uitextfielddelegate, uialertviewdelegate.

In. m, the main is to set the display coordinates, as well as keyboard hiding and several other methods

Inside the Viewdidload method:

-(void) Viewdidload {

[Super Viewdidload];

Self.view.backgroundColor = [Uicolor Whitecolor];

_codeview = [[CodeView alloc]initwithframe:cgrectmake (20, 40, 150, 40)];

[Self.view Addsubview:_codeview];

Hint text

UILabel * label = [[UILabel alloc]initwithframe:cgrectmake (190, 40, 100, 40)];

Label.text = @ "Click on the image for verification Code";

Label.font = [Uifont systemfontofsize:12];

Label.textcolor = [Uicolor Graycolor];

[Self.view Addsubview:label];

Add Input Box

_inputtextfield = [[Uitextfield alloc]initwithframe:cgrectmake (20, 100, 150, 40)];

_inputtextfield.layer.bordercolor = [[Uicolor Lightgraycolor]cgcolor];

_inputtextfield.layer.borderwidth = 2.0;

_inputtextfield.layer.cornerradius = 5.0;

_inputtextfield.font = [Uifont systemfontofsize:21];

_inputtextfield.placeholder = @ "Please enter the verification code";

_inputtextfield.clearbuttonmode = uitextfieldviewmodewhileediting;

_inputtextfield.backgroundcolor = [Uicolor Clearcolor];

_inputtextfield.textalignment = Nstextalignmentcenter;

_inputtextfield.returnkeytype = Uireturnkeydone;

_inputtextfield.delegate = self;

[Self.view Addsubview:_inputtextfield];

Add gestures to hide the keyboard

UITapGestureRecognizer * Tapgesturerecognizer = [[UITapGestureRecognizer alloc]initwithtarget:self Action: @selector ( Taptohidethekeyboard:)];

Tapgesturerecognizer.cancelstouchesinview = NO;

[Self.view Addgesturerecognizer:tapgesturerecognizer];

}

Two ways to hide the keyboard

#pragma Mark--tap

-(void) Taptohidethekeyboard: (UITapGestureRecognizer *) tap{

[_inputtextfield Resignfirstresponder];

}

-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{

[_inputtextfield Resignfirstresponder];

}

Click the keyboard return to disappear keyboard method

#pragma Mark--uitextfielddelegate

-(BOOL) Textfieldshouldreturn: (Uitextfield *) textfield{

if ([_inputtextfield.text isequaltostring:_codeview.changestring] | | [_inputtextfield.text isequaltostring:[_codeview.changestring lowercasestring]]) {

Popup correct

Uialertview * Alertview = [[Uialertview alloc]initwithtitle:@] Congratulations "message:@" verification Success "Delegate:self cancelbuttontitle:@" OK "Otherbuttontitles:nil";

[Alertview show];

}else{

Verification code mismatch, Verification code and input box shaking

Cakeyframeanimation * animation = [Cakeyframeanimation animationwithkeypath:@ "transform.translation.x"];

Animation.repeatcount = 1;

Animation.values = @[@-20,@20,@-20];

[_codeview.layer addanimation:animation Forkey:nil];

[_inputtextfield.layer addanimation:animation Forkey:nil];

}

return YES;

}

Click OK button to retract the keyboard method

#pragma Mark--uialertviewdelegate

-(void) Alertview: (Uialertview *) Alertview Clickedbuttonatindex: (Nsinteger) buttonindex{

Empty the contents of the input box, retract the keyboard

if (Buttonindex = = 0) {

_inputtextfield.text = @ "";

[_inputtextfield Resignfirstresponder];

}

}

In this way, the function is complete.

The main points of knowledge in this place are:

1. Draw the line;

2. Generate randomly generated characters

3. Make the keyboard disappear

On the basis of the original blog, added a case-insensitive small function.

Iphone:ios interface, generate random verification code locally

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.