效果如上所示。
主要的代码:
// // JieSuo.m // 手势解锁 // // Created by 键盘上的舞者 on 15/8/17. // Copyright (c) 2015年 键盘上的舞者. All rights reserved. // #import "JieSuo.h" @interface JieSuo() @property(nonatomic,strong) NSMutableArray *btns; @property(nonatomic,assign) CGPoint pointP; @end @implementation JieSuo -(NSMutableArray *)btns { if(_btns==nil) { _btns=[NSMutableArray array]; } return _btns; } -(id)initWithCoder:(NSCoder *)aDecoder { if(self=[super initWithCoder:aDecoder]) { [self addBtns]; } return self; } -(void)addBtns { for(int i=0;i<9;i++){ UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom]; btn.tag=i+1; [btn setImage:[UIImage imageNamed:@"gesture_node_normal"] forState:UIControlStateNormal]; [btn setImage:[UIImage imageNamed:@"gesture_node_highlighted"] forState:UIControlStateSelected]; btn.userInteractionEnabled=NO; [self addSubview:btn]; } } -(void)layoutSubviews { [super layoutSubviews]; CGFloat col=0; CGFloat row=0; CGFloat btnW=74; CGFloat btnH=74; CGFloat btnX=0; CGFloat btnY=0; CGFloat tolcol=3; CGFloat margin=(self.bounds.size.width -btnW*3)/(tolcol +1); for(int i=0;i<self.subviews.count;i++){ UIButton *btn=self.subviews[i]; col = i % 3; row = i / 3; btnX=margin+(margin+btnW)*col; btnY=(btnH+margin)*row; btn.frame=CGRectMake(btnX, btnY, btnW, btnH); } } //获取触摸点 -(CGPoint)pointWithTouches:(NSSet *)touches { UITouch *touch=[touches anyObject]; return [touch locationInView:self]; } //获取触摸按钮 -(UIButton *)buttonWithPoint:(CGPoint)point { for(UIButton *btn in self.subviews){ if(CGRectContainsPoint(btn.frame, point)){ return btn; } } return nil; } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint pos=[self pointWithTouches:touches]; UIButton *btn=[self buttonWithPoint:pos]; if(btn&&btn.selected==NO){ btn.selected=YES; [_btns addObject:btn]; } } -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint pos=[self pointWithTouches:touches]; _pointP=pos; UIButton *btn=[self buttonWithPoint:pos]; if(btn && btn.selected==NO){ btn.selected=YES; [_btns addObject:btn]; } [self setNeedsDisplay]; } -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { // NSMutableString *str=[[NSMutableString alloc] init]; // for (UIButton *btn in _btns) { // [str appendFormat:@"%d",btn.tag]; // } // NSLog(@"密码是:%@",str); //退出的时候清楚所有手势 [self.btns makeObjectsPerformSelector:@selector(setSelected:) withObject:@NO]; [_btns removeAllObjects]; [self setNeedsDisplay]; } - (void)drawRect:(CGRect)rect { UIBezierPath *path=[UIBezierPath bezierPath]; for (int i=0; i<self.btns.count; i++) { UIButton *btn=_btns[i]; if(i==0){ [path moveToPoint:btn.center]; }else{ [path addLineToPoint:btn.center]; } } [path addLineToPoint:_pointP]; path.lineWidth=8; path.lineJoinStyle=kCGLineJoinRound; [[UIColor greenColor] set]; [path stroke]; } @end