IOS generates a local verification code

Source: Internet
Author: User

IOS generates a local verification code

Verification codes are often used in Application Registration, login, or payment confirmation interfaces. Some of the verification codes are sent via mobile phones, and some are clicked locally to obtain them, the dynamic verification code obtained by sending the mobile phone can be implemented using a third-party class library. You can click to obtain the dynamic verification code locally. Next we will explain in detail the process of generating the dynamic verification code locally.

<1> Import CoreGraphics. framework

<2> The Verification Code encapsulates a UIView, which is directly added to the interface when used.

CaptchaView. h

 
# Import
 
  
@ Interface CaptchaView: UIView @ property (nonatomic, retain) NSArray * changeArray; // string material array @ property (nonatomic, retain) NSMutableString * changeString; // The verification code string @ end
 

CaptchaView. m

 
# Import CaptchaView. 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 attributes: arc4random () % 5 + 15] @ implementation attributes @ synthesize changeString, changeArray) initWithFrame :( CGRect) frame {if (self = [super initWithFrame: frame]) {self. layer. cornerRadius = 5.0; // set the layer rounded corner radius self. layer. masksToBounds = YES; // hide the boundary self. backgroundColor = kRandomColor; // display a Random verification code [self changeCaptcha];} return self ;}# pragma mark to replace the verification code and obtain the string of the changed verification code-(void) changeCaptcha {// <1> randomly extracts the corresponding numbers of characters from the character array to form a verification code string // The array contains all optional characters, which can be letters, it can also be Chinese self. 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, @ Jie, @ UI, @, @ Yu, nil]; // if you can determine the maximum required capacity, use initWithCapacity: to set it, the advantage is that when the number of elements does not exceed the capacity, you do not need to re-allocate the NSMutableString * getStr = [[NSMutableString alloc] initWithCapacity: kCharCount]; self. changeString = [[NSMutableString alloc] initWithCapacity: kCharCount]; // randomly selects the desired number of characters from the array and concatenates them into a string for (int I = 0; I <kCharCount; I ++) {NSInteger index = arc4random () % ([self. changeArray count]-1); getStr = [self. changeArray objectAtIndex: index]; self. changeString = (NSMutableString *) [self. changeString stringByAppendingString: getStr];} // <2> obtain the string from the network, and then draw the string locally (the Network Acquisition step is omitted here)/self. changeString = [NSMutableString stringWithString: @ Jerry Education];} # This is called when pragma mark clicks view. Because the current class itself is UIView, you can click Change verification code to directly write it to this method, no more gestures-(void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {// click the interface to switch the verification code [self changeCaptcha]; // setNeedsDisplay calls the drawRect method to draw the view [self setNeedsDisplay];} # pragma mark drawing interface (1. UIView is automatically called after initialization; 2. call the setNeedsDisplay method automatically)-(void) drawRect :( CGRect) rect {// rewrite the parent class method. First, call the parent class method [super drawRect: rect]; // set the random background color self. backgroundColor = kRandomColor; // obtain the string of the verification code to be displayed. Calculate the approximate position NSString * text = [NSString stringWithFormat: @ % @, self. changeString]; CGSize cSize = [@ S sizeWithAttributes: @ {NSFontAttributeName: [UIFont systemFontOfSize: 20]}]; int width = rect. size. width/text. length-cSize. width; int height = rect. size. height-cSize. height; CGPoint point; // draw each character in sequence. You can set the font size, color, style, and other 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}];} // before calling drawRect: the system will press a CGContextRef to the stack, call UIGraphicsGetCurrentContext () to obtain the CGContextRef context = UIGraphicsGetCurrentContext () on the top of the stack; // set the width of CGContextSetLineWidth (context, kLineWidth ); // draw an interference color line for (int I = 0; I <kLineCount; I ++) {// set the random color of the line UIColor * color = kRandomColor; CGContextSetStrokeColorWithColor (context, [color CGColor]); // set the starting point of the line pX = arc4random () % (int) rect. size. width; pY = arc4random () % (int) rect. size. height; CGContextMoveToPoint (context, pX, pY); // you can specify the line endpoint pX = arc4random () % (int) rect. size. width; pY = arc4random () % (int) rect. size. height; CGContextAddLineToPoint (context, pX, pY); // specifies CGContextStrokePath (context); }}@ end
<3> Add a verification code on the page

ViewController. m

 
# Import ViewController. h # import CaptchaView. h @ interface ViewController ()
 
  
{CaptchaView * _ captchaView; UITextField * _ input;} @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // display the verification code interface _ captchaView = [[CaptchaView alloc] initWithFrame: CGRectMake (20, 40,150, 40)]; [self. view addSubview: _ captchaView]; // The prompt text UILabel * label = [[UILabel alloc] initWithFrame: CGRectMake (190, 40,100, 40)]; label. text = @ Click image for verification code; label. font = [UIFont systemFontOf Size: 12]; label. textColor = [UIColor grayColor]; [self. view addSubview: label]; // Add the input box _ input = [[UITextField alloc] initWithFrame: CGRectMake (20,100,150, 40)]; _ input. layer. borderColor = [UIColor lightGrayColor]. CGColor; _ input. layer. borderWidth = 2.0; _ input. layer. corneradius = 5.0; _ input. font = [UIFont systemFontOfSize: 21]; _ input. placeholder = @ enter the verification code !; _ Input. clearButtonMode = UITextFieldViewModeWhileEditing; _ input. backgroundColor = [UIColor clearColor]; _ input. textAlignment = NSTextAlignmentCenter; _ input. returnKeyType = UIReturnKeyDone; _ input. delegate = self; [self. view addSubview: _ input] ;}# method in The pragma mark input box protocol, click return BUTTON-(BOOL) textFieldShouldReturn :( UITextField *) textField {// determine whether the input is the verification code displayed in the verification image if ([_ input. text isw.tostring: _ captchaView. changeString]) {// The warning prompt is displayed correctly. UIAlertView * alview = [[UIAlertView alloc] initWithTitle: @ congratulations ^ o ^ message: @ delegate: self cancelButtonTitle: @ OK otherButtonTitles: nil, nil]; [alview show];} else {// verification does not match. The verification code and input box shake CAKeyframeAnimation * anim = [CAKeyframeAnimation animationWithKeyPath: @ transform. translation. x]; anim. repeatCount = 1; anim. values = @ [@-20, @ 20, @-20]; [_ captchaView. layer addAnimation: anim forKey: nil]; [_ input. layer addAnimation: anim forKey: nil];} return YES;} # method in The pragma mark warning box-(void) alertView :( UIAlertView *) alertView clickedButtonAtIndex :( NSInteger) buttonIndex {// clear the content of the input box and retrieve the keyboard if (buttonIndex = 0) {_ input. text = @; [_ input resignFirstResponder] ;}}@ end
 

 

For more information, clickView Source CodeRun the test in person.

 

Related Article

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.