Custom Gestures Ching controls

Source: Internet
Author: User

First, the use of controls

Mimic the app's gesture unlock feature on the market, implement small controls, and encapsulate the controls on a UIView

Second, the core principle of technology

1. Touch Events

(1) UIView Touch Three Touch response events: Start, move, end

(2) cgrectcontainspoint determine the location of the touch point

2. quartz2d Drawing

(1) redrawing of the DrawRect

(2) Uibezierpath Bezier curve

3. Block success and Failure callback

Third, the realization of ideas

1, unlock the keyboard of the 9 small icons, will be based on the verification process and change the color, so consider using UIButton implementation, because UIButton can be set according to different states, and to obtain a different picture. The button itself does not require a click event implementation.

2, touch the process, the realization of touch event three methods:

(1) At the beginning to determine whether the touch point on a button, and then change the state of the button, thus achieving "light".

(2) Set up an array to record each button that is "lit"

(3) Draw the connection according to the center point of the button

(4) During the move, continue the "light" button and record

(5) The end of the touch, logical judgment, whether to unlock the success, unlock the password with the button tag splicing (integer string). Depending on the success, change the state of the button on the interface, and then redraw

(6) A callback for success or failure

Iv. Source Code

1. h file

@interface Zqgestureunlockview:uiview /* *   instance dissolve lock keyboard, wide height 320*320,9 button, background black * *  @param frame    x, y available *  @param password Enter a string consisting of 1~9 array, cannot be duplicated *  @param success  unlock successful callback *  @param fail     unlock failed callback * * *  /+ (instancetype) Unlockwithframe: (CGRect) frame Password: (NSString *) Password successblock: (void(^) ()) Success Failblock: ( void (^) ()) fail; @end

2, macro definition and private variable definition

//button to display the number of columns#defineCol 3//Total Buttons#defineSum 9//width and height of the button#defineICONWH 80//color of lines in default state#defineZqlinecolor [Uicolor colorwithred:0.0 green:170/255.0 blue:255/255.0 alpha:0.5]@interfaceZqgestureunlockview ()//Record the selected button@property (nonatomic,strong) Nsmutablearray *Clickbtnarray;//record the color of the connection@property (nonatomic,strong) Uicolor *LineColor;//record the moment's touch point coordinates, the moment is the newest point@property (nonatomic,assign) cgpoint currentpoint;//user-specified password@property (nonatomic,copy) NSString *password;//block of a successful callback@property (nonatomic,copy)void(^success) ();//failed callback block@property (nonatomic,copy)void(^fail) ();@end

3. Method implementations in. m files

//Initialize Method+ (Instancetype) Unlockwithframe: (CGRect) frame Password: (NSString *) Password Successblock: (void(^) ()) Success Failblock: (void(^) ()) fail{Zqgestureunlockview* MainView =[[Self alloc]init]; Mainview.frame= CGRectMake (frame.origin.x, FRAME.ORIGIN.Y, the, the); Mainview.password=password; Mainview.success=success; Mainview.fail=fail; //Generate button[MainView setupbuttons]; returnMainView;}//Generate button-(void) setupbuttons{//Generate button     for(inti =1; i<sum+1; i++) {UIButton* Button =[UIButton Buttonwithtype:uibuttontypecustom]; [Button setimage:[uiimage imagenamed:@"Gesture_node_normal"] Forstate:uicontrolstatenormal]; [Button setimage:[uiimage imagenamed:@"gesture_node_highlighted"] forstate:uicontrolstatehighlighted]; [Button setimage:[uiimage imagenamed:@"Gesture_node_error"] forstate:uicontrolstatedisabled]; //add tag to the buttonButton.tag =i; //initial state, so that the button is not interactive, the button is displayed, no click eventButton.userinteractionenabled=NO; [Self Addsubview:button];
} //record the color of the default lineSelf.linecolor =Zqlinecolor; //Set TransparentSelf.backgroundcolor = [Uicolor colorwithpatternimage:[uiimage imagenamed:@"BG"]];}//Layout child controls-(void) layoutsubviews{[Super Layoutsubviews]; CGFloat margin= (SELF.FRAME.SIZE.WIDTH-COL*ICONWH)/2; [Self.subviews Enumerateobjectsusingblock:^ (UIButton * _nonnull obj, Nsuinteger idx, BOOL *_nonnull stop) {CGFloat x= Idx%col * (ICONWH +margin); CGFloat y= Idx/col * (ICONWH +margin); Obj.frame=CGRectMake (x, Y, ICONWH, ICONWH); }];}#pragmaMark-Touch start, record the beginning of the point-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (Uievent *)Event{Uitouch* Touch =Touches.anyobject; Cgpoint StartPoint=[Touch locationinview:self]; //traverse all buttons to determine if the position of the touch is within the button range[self.subviews enumerateobjectsusingblock:^ (UIButton * _nonnull obj, Nsuinteger idx, BOOL *_nonnull stop) {BOOL Iscontain=Cgrectcontainspoint (Obj.frame, startPoint); //if it is within a range of buttons and the button is not lit. if(Iscontain && obj.highlighted==NO) { //Change button status to highlightobj.highlighted =YES; //Log This button to the "Check button marker array"[Self.clickbtnarray addobject:obj]; } //if it's not inside a button, set the button to not highlight (regardless of whether it was originally highlighted) Else{obj.highlighted=NO; } }]; //Save the coordinates of the moment for drawing linesSelf.currentpoint =StartPoint;}#pragmaMark-touch move, same as to determine the position of the button-(void) touchesmoved: (Nsset<uitouch *> *) touches withevent: (Uievent *)Event{Uitouch* Touch =Touches.anyobject; Cgpoint Movepoint=[Touch locationinview:self]; //determines whether the position of the touch move is within the button range, traversing all buttons[Self.subviews enumerateobjectsusingblock:^ (UIButton * _nonnull obj, Nsuinteger idx, BOOL *_nonnull stop) {BOOL Iscontain=Cgrectcontainspoint (Obj.frame, movepoint); //if the touch range is on a button and the button is not lit if(Iscontain && obj.highlighted==NO) {obj.highlighted=YES; [Self.clickbtnarray Addobject:obj]; } }]; //Save the coordinates of the momentSelf.currentpoint =Movepoint; //call view redraw, draw lines[self setneedsdisplay];}#pragmaMark-Touch ends, makes logical judgments, redraws lines, displays the connected state after the judgment-(void) touchesended: (Nsset<uitouch *> *) touches withevent: (Uievent *)Event{ //Assemble user's password after the end of the gesturensmutablestring * passwordstring =[nsmutablestringstring]; [Self.clickbtnarray Enumerateobjectsusingblock:^ (UIButton * _nonnull obj, Nsuinteger idx, BOOL *_nonnull stop) { //Synthetic Password[passwordstring AppendFormat:@"%ld", Obj.tag]; }]; //Proof of the correct password if([passwordstring IsEqualToString:self.password]) {//add delay, is to give a short pause after the password is correctDispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (0.5* nsec_per_sec)), Dispatch_get_main_queue (), ^{ //Remove the Highlight button first[Self.clickbtnarray enumerateobjectsusingblock:^ (UIButton * _nonnull obj, Nsuinteger idx, BOOL *_nonnull stop) {obj.highlighted=NO; }]; //and empty the array .[Self.clickbtnarray removeallobjects]; //Last Redraw[self setneedsdisplay]; }); //callback to perform validation successself.success (); } //Password Error Else { //Turn off view interaction first and avoid error actionsSelf.userinteractionenabled=NO; //Highlight the button first, set it to the enabled state, and turn the connection red .[Self.clickbtnarray enumerateobjectsusingblock:^ (UIButton * _nonnull obj, Nsuinteger idx, BOOL *_nonnull stop) {obj.enabled=NO; Obj.highlighted=NO; }]; Self.linecolor=[Uicolor Redcolor]; [Self setneedsdisplay]; //delay, then clear .Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (0.5* nsec_per_sec)), Dispatch_get_main_queue (), ^{ //enable the button first[Self.clickbtnarray enumerateobjectsusingblock:^ (UIButton * _nonnull obj, Nsuinteger idx, BOOL *_nonnull stop) {obj.enabled=YES; }]; //then empty the Highlight button array[Self.clickbtnarray removeallobjects]; //Redraw[self setneedsdisplay]; //finally in the open interactionSelf.userinteractionenabled=YES; //Restore default Line ColorSelf.linecolor=Zqlinecolor; }); } //set Currentpoint to the center of the last highlighted button, so that when the touch is released, the connection does not show the extra "tail".UIButton * btn =Self.clickBtnArray.lastObject; Self.currentpoint=Btn.center;} //Redraw the View-(void) DrawRect: (cgrect) rect{Uibezierpath* Path =[Uibezierpath Bezierpath]; [Self.clickbtnarray Enumerateobjectsusingblock:^ (UIButton * _nonnull obj, Nsuinteger idx, BOOL *_nonnull stop) { //Set Start point if(idx==0) {[path moveToPoint:obj.center]; } //Set Add Point Else{[path addLineToPoint:obj.center]; } }]; //line Color, Width[Path Setlinewidth:Ten]; Uicolor* color =Self.linecolor; [Color Setstroke]; //Setting up Connections[path Setlinejoinstyle:kcglinejoinround]; [Path Setlinecapstyle:kcglinecapround]; //Add real-time "threads" if(self.clickbtnarray!=Nil) {[path addLineToPoint:self.currentPoint]; } //Drawing[path stroke];}//Lazy Loading-(Nsmutablearray *) clickbtnarray{if(!_clickbtnarray) {_clickbtnarray=[Nsmutablearray array]; } return_clickbtnarray;}

V. Expansion

1, unlock the size of the keyboard can be defined according to the actual situation

2, touch gestures are drawn using a non-repeatable point, this can be improved

3, unlimited number of verification

4. This example is used for entertainment, learning, communication

Custom Gestures Ching controls

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.